CRUD
向数据库中保存记录,修改数据库中记录,删除数据库中记录,查询数据库中记录
package com.imooc.jdbc;
import org.junit.Test;
import java.sql.*;
public class jdbc_demo2 {
@Test
public void demo1(){
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;//查询数据专用
try {
//注册驱动
//Class.forName("com.mysql.cj.jdbc.Driver()");
DriverManager.registerDriver(new com.mysql.cj.jdbc.Driver());
//获得连接
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/jdbctest?useUnicode=true&characterEncoding=UTF-8&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC","root","root");
//获取SQL语句对象
stmt = conn.createStatement();
//编写SQL
//插入 String sql = "insert into user values(null,'eee','123','王六')";
//更新修改 String sql = "update user set username = 'qqq',password='456',name='赵六' where uid=6";
//删除 String sql = "delete from user where uid=6";
//增删改执行SQL
//int i = stmt.executeUpdate(sql);
//if(i>0){
// System.out.println("成功");
//}
//查询流程
String sql = "select * from user where uid=1";
rs = stmt.executeQuery(sql);
while (rs.next()){
System.out.println(rs.getInt("uid")+" "+rs.getString("username")+" "+rs.getString("password"));
}
}catch (Exception e){
e.printStackTrace();
}finally {
//释放
if(stmt!=null){
try {
stmt.close();
}catch (SQLException e){
e.printStackTrace();
}
stmt = null;
}
if(conn!=null){
try {
conn.close();
}catch (SQLException e){
e.printStackTrace();
}
conn = null;
}
if(rs!=null){
try {
rs.close();
}catch (SQLException e){
e.printStackTrace();
}
rs = null;
}
}
}
}