ステップ
ソースコード
DBUtilsクラス
package com.csu.db;
import java.sql.*;
public class DBUtils {
public static Connection getConnection(){
try {
//[1/7] 加载JDBC的驱动
Class.forName("com.mysql.cj.jdbc.Driver");
//[2/7] 定义url连接参数
String url = "jdbc:mysql://localhost:3306/company?useUnicode=true&autoReconnect=true&characterEncoding=UTF-8&useSSL=false&serverTimezone=GMT";
String username = "root";
String password = "111111";
//[3/7] 创建连接
Connection conn = DriverManager.getConnection(url,username,password);
return conn;
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}
return null;
}
//[7/7] 关闭连接
public static void close(ResultSet rs, Statement st,Connection conn){
if(rs != null){
try {
rs.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if(st != null){
try {
st.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if(conn != null){
try {
conn.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
}
DeptDaoImplクラス
package com.csu.dao;
import com.csu.db.DBUtils;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class DeptDaoImpl {
//新建部门
public int addDept(String dname,String loc){
Connection conn = DBUtils.getConnection();;// 连接对象
// [4/7] 创建sql语句的预编译对象
PreparedStatement ps = null;
try {
String sql = "INSERT INTO dept VALUES(null,?,?)";
ps = conn.prepareStatement(sql);
ps.setString(1,dname);
ps.setString(2,loc);
// [5/7] 执行DML语句
//返回受影响行数
ruturn ps.executeUpdate();
} catch (SQLException throwables) {
throwables.printStackTrace();
}finally {
//关闭资源
DBUtils.close(null,ps,conn);
}
return 0;
}
}