创建一个名为Books的数据库,并在其中建立一个名为book_message的表,字段包括书名、作者、出版社、出版时间和价格。编写一个应用程序,实现对该数据库中数据的添加、修改、删除和查询功能。

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);
}
}
}

}
}

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值