com.mysql.jdbc.Driver jdbc:mysql://localhost:3306/students?useUnicode=true&characterEncoding=utf-8 &zeroDateTimeBechavior=convertToNull&serverTimeZone=UTC"; root 123456 5 10 3000 com.mysql.jdbc.Driver jdbc:mysql://localhost:3306/students?useUnicode=true&characterEncoding=utf-8 &zeroDateTimeBechavior=convertToNull&serverTimeZone=UTC"; root 123456 5 8 3000
定义方法用于加载数据库的一些信息。
public void getConnection() {
//1.加载插件
try {
Class.forName("com.mysql.jdbc.Driver");
//2.准备连接数据的信息:要连接的数据库的地址 用户名 密码
String url="jdbc:mysql://localhost:3306/students?useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull&serverTimeZone=UTC";
String username="root";
String password="123456";
//使用设备管理器类根据提供的信息连接数据库
con=DriverManager.getConnection(url, username, password);
} catch (Exception e) {
e.printStackTrace();
}
}
增
@org.junit.Test
public void test1() {
//添加数据
getConnection();
//判断是否连接成功
if (con!=null) {
//准备要执行的添加sql语句
//在jdbc连接数据库中,使用占位符?
String sql="insert into tb_students(name,age) VALUES(?,?)";
//准备执行sql语句
try {
PreparedStatement ps=con.prepareStatement(sql);
ps.setString(1, "少年的你");
ps.setInt(2, 22);
int count=ps.executeUpdate();
if (count>0) {
System.out.println("添加成功");
}
//执行完成之后,要断开数据库连接
ps.close();
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
删
@org.junit.Test
public void test3() {
//删除语句
getConnection();
if (con!=null) {
String sql="delete from tb_students where id=?";
try {
PreparedStatement ps=con.prepareStatement(sql);
ps.setInt(1, 5);
int i=ps.executeUpdate();
if (i>0) {
System.out.println("删除成功");
}
ps.close();
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
改
@org.junit.Test
public void test2() {
//修改语句
getConnection();
if (con!=null) {
String sql="update tb_students set age=? where id=?";
try {
PreparedStatement ps=con.prepareStatement(sql);
ps.setInt(1, 15);
ps.setInt(2, 1);
int i=ps.executeUpdate();
if (i>0) {
System.out.println("修改成功");
}
ps.close();
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
查
@org.junit.Test
public void test4() {
//查询语句
//根据id=1查询学生的信息
getConnection();
if (con!=null) {
String sql="select * from tb_students where id=?";
try {
PreparedStatement ps=con.prepareStatement(sql);
ps.setInt(1, 1);
ResultSet rs=ps.executeQuery();
//因为查询出来的数据是一张表的结构,游标默认停留在第一行,是字段名
//所有需要获得的数据要从第二行开始
if (rs.next()) {
int id=rs.getInt(1);
String name=rs.getString(2);
int age=rs.getInt(3);
System.out.println(id+"--"+name+"--"+age);
}
//断开连接
rs.close();
ps.close();
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}



