package com.wr.demo;
import java.sql.*;
// JDBC编程六部
// 1.注册驱动
// 2、获取连接
// 3.获取数据库操作对象(Statement专门执行sql语句的)
// 4、执行sql
// 5、处理查询结果集
// 6、释放资源
public class test01 {
public static void main(String[] args) {
Connection conn = null;
Statement stat = null;
ResultSet rest = null;
try {
// 1.注册驱动(这里表示注册的是mysql数据库驱动,使用的是反射机制实现的,老版本mysql这里参数是"com.mysql.jdbc.Driver")
Class.forName("com.mysql.cj.jdbc.Driver");
// 2、获取连接
注意:后面的参数jdbc:mysql表示连接的mysql数据库,后面localhost表示连接的是本地ip地址,后面3306是端口号,Book是要操作的数据库名,root和823624分别是我数据库的用户名和密码。
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/Books","root","823624");
// 3.获取数据库操作对象(Statement专门执行sql语句的)
stat = conn.createStatement();
//查询
String sql = "select book_name,price from book_message ";
//增
String sql1 = "insert into book_message values('勇士总冠军','方鸡','狗叫出版社','2024-10-18','1111.1')";
//改
String sql2 = "update book_message set author = '王鸡刚' where book_name = '农夫山泉'";
//删
String sql3 = "delete from book_message where price = '3'";
int s1 = stat.executeUpdate(sql1);
int s2 = stat.executeUpdate(sql2);
int s3 = stat.executeUpdate(sql3);
System.out.println(s1==1?"新增成功":"新增失败");
System.out.println(s2==1?"修改成功":"修改失败");
System.out.println(s3==1?"删除成功":"删除失败");
rest = stat.executeQuery(sql);
while (rest.next()){
String book_name = rest.getString("book_name");
String price = rest.getString("price");
System.out.println("书名为:"+book_name+","+"价格为:"+price);
}
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
} catch (SQLException e) {
throw new RuntimeException(e);
} finally {
if (rest!=null){
try {
rest.close();
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
if (stat!=null){
try {
stat.close();
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
if (conn!=null){
try {
conn.close();
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
}
}
}