1.创建数据库的连接对象Connection 和 mysql驱动对象 Driver(注册驱动)都是固定写法,应该写在工具类中,可以共同调用
2. 属性文件保存连接数据库常用字段:
url=jdbc:mysql://localhost:3306/db102
user=root
password=root
driver=com.mysql.jdbc.Driver
3.
public class JDBCUtil {
private static String url;
private static String driver;
private static String user;
private static String pwd;
//静态代码块的特点 ? :加载字节码的时候执行一次,所以防止重复访问文件
static{
try {
FileInputStream in = new FileInputStream("./db.properties");
Properties pro = new Properties();
pro.load(in);
url = pro.getProperty("url");
driver = pro.getProperty("driver");
user = pro.getProperty("user");
pwd = pro.getProperty("password");
Class.forName(driver);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static Connection getConnection(){
Connection connection = null;
try {
connection = DriverManager.getConnection(url, user, pwd);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return connection;
}
public static void closeConnection(Connection conn, Statement state) {
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (state !=null) {
try {
state.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public static void closeConnection(Connection conn, Statement state,ResultSet set) {
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (state !=null) {
try {
state.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (set !=null) {
try {
set.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}