DML操作
1. 插入记录
解决插入中文乱码问题。
jdbc:mysql://localhost:3306/db4?characterEncoding=UTF-8 characterEncoding=UTF-8 指定字符的编码、解码格式。
package com.lagou.jdbc02;
import com.lagou.utils.JDBCUtils;
import org.junit.Test;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
public class TestDML {
/*
* 插入数据
* */
@Test //添加类似main方法的jar包,
public void testInsert() throws SQLException {
//1.通过JDBCUtils工具类 获取连接
Connection con = JDBCUtils.getConnection();
//2.获取Statement对象
Statement statement = con.createStatement();
//2.1 编写SQL,第一个字段为主键自增,因此直接写null让其自增就可以了
String sql = "insert into jdbc_user values(null,'张百万','123','2020/11/11')";
//2.2 执行SQL
int i = statement.executeUpdate(sql);
System.out.println(i);
//3.关闭流
JDBCUtils.close(con,statement);
}
/*
* 更新操作 根据id修改用户名
* */
@Test
public void testUpdate() throws SQLException {
Connection connection = JDBCUtils.getConnection();
Statement statement = connection.createStatement();
String sql = "update jdbc_user set username = '刘能' where id = 1";
statement.executeUpdate(sql);
JDBCUtils.close(connection,statement);
}
/*
* 删除操作
* 删除 id为 1 和 2 的数据
*
* */
@Test
public void testDelete() throws SQLException {
Connection connection = JDBCUtils.getConnection();
Statement statement = connection.createStatement();
String sql = "delete from jdbc_user where id in(1,2)";
statement.executeUpdate(sql);
JDBCUtils.close(connection,statement);
}
}
节选自拉钩教育JAVA系列课程