在IDEA中JDBC对于数据库的基本增删查改操作
在Java的项目开发中,大多数操作都需要与数据库有密切的联系,因此掌握JDBC的相关知识与基本操作是非常有必要的。接下来将通过对于一个简单的学生表Stu的增删查改的具体操作步骤为例,分享一些有关JDBC的基本操作方法。
一、相关jar包导入和数据库表格建立
在IDEA中新创建一个Java项目之后,需要找到lib包,将对应的MySQL版本的jar包导入其中,并且右键单击,选择Add as library。jar包就导入成功了。
二.了解关于JDBC的七大操作步骤
1.在项目创建好了之后,首先要加载数据库驱动。
在这里使用try { //加载数据库驱动 Class.forName("com.mysql.jdbc.Driver");
2.在加载好数据库驱动之后,就要建立与数据库的链接
//2.创建连接
connection=DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/idea?useSSL=true&" +
"characterEncoding=utf-8&user=root&password=1060070776");
System.out.println("创建连接成功");
在这里需要注意user=xxx和password=xxxxx这里是自己的数据库的用户名和密码。可以用一个System.out.println(“创建连接成功”)通过打印输出来测试链接是否成功建立。
3.第三步就是写相关的sql语言来实现对应功能,在这里以查询功能为例,相关sql实现代码如下
//3.写sql String sql="seleect * from stu";
其他的例如添加,删除和修改操作就使用:Insert Delete 以及Update语句实现
4.在写完sql语句后,我们希望得到statement对象。要知道,如果要执行一个sql语句,就必须要有一个java.sql.Statement实例对象。在这里我们通过使用preparedStatement来执行一个动态过程(一般用Statement实现静态实例)
/4.得到statement对象
statement=connection.prepareStatement(sql);
5.sql语句写完并且获取到对象后,就是一个执行sql语句的过程。在Statement接口中提供了三种sql语句:1.executeQuery 2.executeUpdate 3.execute(sqlString)
这里我们通过执行sql语句得到一个结果集的代码实现为
//5.执行sql 得到结果集
resultSet=statement.executeQuery();
6.在这里我们进行的是查询操作,所以以查询为例,需要获得一个结果集。
//6.处理结果集
while(resultSet.next()){}
int id=resultSet.getInt(1);
String sex= resultSet.getString(2);
String name=resultSet.getString(3);
7.在操作完成之后,最后一步是关闭JDBC对象并且回收数据库资源。这里需要注意到的是,关闭的顺序和声明的顺序是相反的。具体为:1.先关闭resultSet 2.再关闭对象preparedStatement 3.最后关闭连接即 connection。具体代码参考如下:
//7.关闭资源
} catch (Exception e) {
e.printStackTrace();
}finally{
if (resultSet!=null)
try {
resultSet.close();
} catch (SQLException e) {
e.printStackTrace();
}
if(statement!=null) {
try{
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (connection!=null){
try{
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
至此有关于JDBC的基本增删改查操作就是这些。
三.但是我们可以发现,每个功能中都有许多的重复的操作,包括加载驱动,链接数据库和最后的关闭链接这些。于是我们可以使用到封装的思想,将这些重复的部分封装在一个工具类中。
public class db {
public static Connection connect() {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection connect = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/db_user?useSSL=true&characterEncoding=utf-8&user=root&password=123");
return connect;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static void realese(Connection connect, PreparedStatement statement, ResultSet result){
if(connect!=null) {
try{
connect.close();}
catch (SQLException e){
e.printStackTrace();
}
}
if(statement!=null){
try{
statement.close();
}
catch(SQLException e){
e.printStackTrace();
}
}
if(result!=null){
try{
result.close();
}
catch(SQLException e){
e.printStackTrace();
}
}
}
}