当前位置: 首页 > 工具软件 > JdbcUtils > 使用案例 >

JDBC创建JDBCUtils 连接数据库

左博学
2023-12-01
package com.m.JDBCUtils;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

public class JDBCUtils {
	private static String classname;
	private static String url;
	private static String username;
	private static String password;
	//使用静态代码块加载驱动
	static {
		Properties properties =new Properties();
		//加载"db.properties"
		try {
			properties.load(new FileReader("db.properties"));
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		//获取db.properties中的值
		classname=properties.getProperty("classname");
		url=properties.getProperty("url");
		username=properties.getProperty("username");
		password=properties.getProperty("password");
	}
	public  static Connection getConnection() throws Exception, IOException {
		Class.forName(classname);
		Connection conn = DriverManager.getConnection(url, username, password);
		if(conn!=null) {
			System.out.println("连接完成");
		}
		return conn;
	}
	public static void closeAll(ResultSet rs,Statement st,Connection con) {
		try {
			if(rs!=null) {
				rs.close();
			}
			
		} catch (SQLException e) {
			
			e.printStackTrace();
		}
		try {
			if(st!=null) {
				st.close();
			}
			
		} catch (SQLException e) {
			
			e.printStackTrace();
		}
		try {
			if(con!=null) {
				con.close();
			}
			
		} catch (SQLException e) {
			
			e.printStackTrace();
		}
		
		
	}
	
	public static void closeAll(Statement st,Connection con) {
		
		try {
			if(st!=null) {
				st.close();
			}
			
		} catch (SQLException e) {
			
			e.printStackTrace();
		}
		try {
			if(con!=null) {
				con.close();
			}
			
		} catch (SQLException e) {
			
			e.printStackTrace();
		}
		
		
	}
	public static void closeAll(Connection con) {
		
		try {
			if(con!=null) {
				con.close();
			}
			
		} catch (SQLException e) {
			
			e.printStackTrace();
		}
		
		
	}
}

package com.m.JDBC;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import com.m.JDBCUtils.JDBCUtils;

public class mysqlTest2 {
	public static void main(String[] args) throws Exception {

		
		Connection conn = JDBCUtils.getConnection();;
		if(conn!=null) {
			System.out.println("连接完成");
		}
		
		Statement statement = conn.createStatement();

		String sql=" select * from department";//查询
		ResultSet i = statement.executeQuery(sql);
		
		while(i.next()) {
			System.out.println(i.getInt(1)+" "+i.getString(2));
		}
		
		JDBCUtils.closeAll(i, statement, conn);
	}
}

 类似资料: