JDBC
jdbc的 增删改查(CRUD)
- C: create 增
- R: query 查
- U: update 改
- D: delete 删
如何通过JDBC 查[executeQuery] 增删改[executeUpdate]数据
--------------------------------------------
新增表记录: 往account表中添加一条记录: null ‘hellen’ 3500
@Test ---> 用反射
public void testAdd() throws Exception {
1.注册驱动
Class.forName( "com.mysql.cj.jdbc.Driver" );
2.获取连接
Connection conn = DriverManager.getConnection(
"jdbc:mysql:///数据库名?characterEncoding=utf-8&serverTimezone=Asia/Shanghai&useSSL=false",
"root", "root" );
3.获取传输器(建立通道)
Statement stat = conn.createStatement();
查看:
语法:executeQuery 只能一行一行查看
4.发送sql到数据库执行,并返回执行结果
ResultSet rs = stat.executeQuery("select * from account");
处理结果(打印到控制台)
rs.next 返回true表示下一行有数据,就会进入循环获取的下一行数据
while(rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
double money = rs.getDouble("money");
System.out.println(id+","+name+","+money);
}
增删改:
语法:executeUpdate 返回的是执行了几行(影响的行数)
4.执行SQL语句, 返回执行结果
String sql = "insert into account value(null, 'hellen', 3500 )";
int rows = stat.executeUpdate(sql);
5.处理结果
System.out.println( "影响的行数为: "+rows );
6.释放资源(越晚获取的越先关闭)
stat.close();
conn.close();
}