WEB03_Day01(下)-JDBC连接MySQL、封装DBUtils工具类
一、JDBC连接MySQL(CRUD)
1.1 删除
/**
* 删除数据
*/
@Test
public void delete() throws Exception {
//1.加载驱动
//2.获取连接对象
String url = "jdbc:mysql://localhost:3306/newdb3?characterEncoding=utf8&useSSL=false&serverTimezone=Asia/Shanghai&rewriteBatchedStatements=true";
String userName = "root";
String password = "root";
Connection conn = DriverManager.getConnection(url,userName,password);
//3.创建命令对象
Statement stat = conn.createStatement();
//4.执行sql
String sqlStr = "DELETE FROM emp WHERE empno=12";
int nums = stat.executeUpdate(sqlStr);
System.out.println("受影响的行数:" + nums);
//5.关闭资源
conn.close();
}
1.2 修改
/**
* 修改数据
*/
@Test
public void update() throws Exception{
Class.forName("com.mysql.cj.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/newdb3?characterEncoding=utf8&useSSL=false&serverTimezone=Asia/Shanghai&rewriteBatchedStatements=true";
String userName = "root";
String password = "root";
Connection conn = DriverManager.getConnection(url,userName,password);
Statement stat = conn.createStatement();
String sqlStr = "UPDATE emp SET sal=1000 WHERE empno=1";
int nums = stat.executeUpdate(sqlStr);
System.out.println(nums);
conn.close();
}
1.3 查询
/**
* 查询数据
*/
@Test
public void select() throws Exception{
Class.forName("com.mysql.cj.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/newdb3?characterEncoding=utf8&useSSL=false&serverTimezone=Asia/Shanghai&rewriteBatchedStatements=true";
String userName = "root";
String password = "root";
Connection conn = DriverManager.getConnection(url,userName,password);
Statement stat = conn.createStatement();
String sqlStr = "SELECT empno,ename FROM emp";
/*
* 查询数据时,返回的是一个ResultSet结果集对象,
* 在结果集对象中包含了查询出来的数据
*/
ResultSet rs = stat.executeQuery(sqlStr);
/*
* 使用rs结果集对象中提供的next方法,进行遍历当前对象中的
* 每一行员工数据内容,根据每位员工的字段信息就可以获取对应字段的数值。
* 结果集对象调用next方法时如果有数据返回值为true,如果没有数据返回值为false
*
*/
// boolean b = rs.next();
// System.out.println(b);
// b = rs.next();
// System.out.println(b);
// System.out.println(rs.getInt(1));
// System.out.println(rs.getString(2));
// //向上移动指针
// b = rs.previous();
// System.out.println(b);
// System.out.println(rs.getInt(1));
// System.out.println(rs.getString(2));
// b = rs.previous();
// System.out.println(b);
while (rs.next()) {
/*
* 获取字段数据的方法:
* 1.根据列的序列号
* 2.根据字段的名字
*/
// int empId = rs.getInt(1);
// String ename = rs.getString(2);
int empId = rs.getInt("empno");
String ename = rs.getString("ename");
System.