jdbcutils工具类封装

今天复习了一下jdbc工具类,所以想写下来测试一下

public class JDBCUtils {
	private static final String driverClassName;
	private static final String url;
	private static final String username;
	private static final String password;
	static {
		driverClassName="com.mysql.jdbc.Driver";
		url="jdbc:mysql://localhost:3306/zu";
		username="root";
		password="123456";
	}
	
//注册驱动	
public static void loadDriver(){
	try {
		Class.forName("com.mysql.jdbc.Driver");
	} catch (ClassNotFoundException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
}

//获得连接
public static Connection getconnection(){
	Connection conn=null;
	loadDriver();
	try {
		conn=DriverManager.getConnection(url,username,password);
	} catch (SQLException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}return conn;
}



//释放资源
public static void  close(Connection conn,Statement st){
	if(conn!=null){
		try {
			conn.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}conn=null;
	}
	if(st!=null){
		try {
			st.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}st=null;
	}
}
public static void close(Connection conn,Statement st,ResultSet rs){
	if(conn!=null){
		try {
			conn.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}conn=null;
	}
	if(st!=null){
		try {
			st.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}st=null;
		if(rs!=null){
			try {
				rs.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}rs=null;
}
}}

测试了一下,还行

public class Demo {
public static void main(String[]args){
	Connection conn=JDBCUtils.getconnection();
	Statement st=null;
	try {
		 st=conn.createStatement();
	} catch (SQLException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
	ResultSet rs=null;
	try {
		 rs=st.executeQuery("INSERT INTO ce(uses,pas) VALUES('123','lin')");
	} catch (SQLException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}finally{
		JDBCUtils.close(conn, st, rs);
	}
}
}

猜你喜欢

转载自blog.csdn.net/dtbk123/article/details/86937931