版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
在jdbc代码中,加载驱动、创建链接、关闭资源的代码都是固定的,可以将这些代码放在一个类里面,这样就可以不用重复写这些代码,节省时间和精力。
新建一个DBUtill类把那几个固定的代码放入该类
package com.lzfthh;
import java.sql.*;
public class Dbutill {
public static Connection getConnection() throws ClassNotFoundException, SQLException {
Class.forName("com.mysql.jdbc.Driver");
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost/zjgm?user=root&password=123456&characterEncoding=utf-8&useSSL=true");
return connection;
}
public static void closeAll(ResultSet resultset,Statement statement,Connection connection) throws SQLException {
if(resultset!=null){
resultset.close();
}
statement.close();
connection.close();
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
主程序代码
package com.lzfthh;
import java.sql.*;
public class test {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
//1 加载驱动
Connection connection = Dbutill.getConnection();
//2 创建链接
System.out.println("创建连接成功");
//3 写sql
String sql ="select * from stu";
//4 得到statement对象
PreparedStatement statement = connection.prepareStatement(sql);
//5 执行sql
ResultSet resultSet =statement.executeQuery();
//6 处理结果集
while (resultSet.next()){
int id =resultSet.getInt(1);
String name =resultSet.getString(2);
int age = resultSet.getInt(3);
System.out.println(id+name+age);
}
//7关闭资源
Dbutill.closeAll(resultSet,statement,connection);
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
</div>
<link href="https://csdnimg.cn/release/phoenix/mdeditor/markdown_views-e44c3c0e64.css" rel="stylesheet">
</div>