由于经常会连接数据库,因此编写了一个工具类,用到时只需要导入即可使用。
package com.guigu.util;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class JdbcUtil {
private static String userName ="root" ;
private static String pass ="root";
private static String url ="jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8";
private static String driver ="com.mysql.jdbc.Driver";
//获得与数据库的连接
public static Connection getConnection(){
Connection conn = null;
try {
Class.forName(driver);//加载数据库驱动
//获得连接 DriverManager
conn = DriverManager.getConnection(url, userName, pass);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return conn;
}
//关闭资源
public static void closeConn(Connection conn,Statement st,ResultSet rest){
if(rest != null){
try {
rest.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(st != null){
try {
st.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(conn != null){
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
Connection conn=getConnection();
System.out.println(conn);
}
}