JDBC第一天
JDBC的组成框图
JDBC API
供开发者调用的接口 -> java.sql和javax.sql
- Driver类
- Connection接口
- Statement接口
- ResultSet接口
JDBC Driver Manager
管理不同的JDBC驱动
JDBC的使用
- 加载数据库驱动
//加载驱动
try {
//获取Driver的运行时类
Class.forName ("com.mysql.cj.jdbc.Driver");
//获取连接
String url = "jdbc:mysql://localhost:3306/library?useUnicode=true&characterEncoding=UTF-8";
String user = "root";
String password = "Csk513434";
}
catch (ClassNotFoundException e) {
e.printStackTrace ();
}
- 获取Connection,Java程序与数据库的一次连接
Connection connection = DriverManager.getConnection (url, user, password);
- 创建Statement对象,执行sql语句
//增加删除修改 使用statement.executeUpdate (sql)
String sql = "insert into book(name,author,publish) values ('承苏凯的故事','承苏凯','苏州出版社')";
String sql = "insert into book(name,author,publish) values ('张三的故事','张三','北京出版社')";
String sql = "update book set name = '李四的书'";
String sql = "delete from student";
Statement statement = connection.createStatement ();
int result = statement.executeUpdate (sql);
System.out.println (result);
- 创建ResultSet对象,如果需要接受返回值,保存Statement执行之后所查询的结果
//删除操作使用 使用statement.executeQuery (sql)
String sql = "select * from book";
Statement statement = connection.createStatement ();
ResultSet resultSet = statement.executeQuery (sql);
while (resultSet.next ()) {
Integer id = resultSet.getInt ("id");
String name = resultSet.getString (2);
String author = resultSet.getString (3);
String address = resultSet.getString (4);
System.out.println (id "-" name "-" author "-" address);
}
总结
学习了如何通过Java程序加载数据库并通过JDBC对数据库的中表进行增删改查的操作,其中增删改是调用statement.executeUpdate()
方法而查询是调用statement.executeQuery ()
,它们的返回类型一个是int,一个是resultSet,需要注意!