JDBC之封装的工具类
import java.sql.*;
public class JDBCUtils {
private static String driver="com.mysql.jdbc.Driver";
private static String url="jdbc:mysql://127.0.0.1:3306/day04";
private static String user="root";
private static String password="root";
static{
try {
Class.forName(driver);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
public static Connection getConnection(){
Connection conn = null;
try {
conn = DriverManager.getConnection(url, user, password);
} catch (Exception e) {
throw new RuntimeException("获取数据库失败");
}
return conn;
}
public static void close(ResultSet rs, Statement stat, Connection conn){
if(rs!=null){
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(stat!=null){
try {
stat.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(conn!=null){
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
对封装的工具类进行调用测试之插入
import org.junit.Test;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
public class Demo03JDBC {
@Test
public void testInsert(){
Connection conn = JDBCUtils.getConnection();
Statement state=null;
try {
state = conn.createStatement();
int i =state.executeUpdate("insert into products(pid,pname,price,flag,category_cid)values('p002','华为1',5000,'1',001),('p003','华为20',6000,'1',001);");
System.out.println(i+"行数据添加成功");
} catch (SQLException e) {
e.printStackTrace();
}finally {
JDBCUtils.close(null,state,conn);
}
}
}