JdbcUtils

JdbcUtils

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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
package com.dwx.jabcstudy;

import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

public class JdbcUtils {
//提升作用域
private static String driver = null;
private static String url = null;
private static String username = null;
private static String password = null;
// 这是一个静态代码块 因此 再倒入这个类时 只会加载一次
static {
try{
InputStream in = JdbcUtils.class.getClassLoader().getResourceAsStream("db.properties"); //这里是去获取配置文件
Properties properties = new Properties(); //这是一个流
properties.load(in); //加载配置文件
driver = properties.getProperty("driver");//这就是获取配置文件中数值的方法
url = properties.getProperty("url");
username = properties.getProperty("username");
password = properties.getProperty("password");
Class.forName(driver);//加载mysql
}catch (Exception e){
System.out.println("出错了!!!");
}finally {

}
}
//获取链接
//方法会返回一个Connection类型的数据
public static Connection getConnection() throws Exception {
return DriverManager.getConnection(url, username, password);
}
//释放资源
public static void release(Connection connection, Statement statement, ResultSet resultSet) throws SQLException {
if(resultSet!=null){
try {
resultSet.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if(statement!=null){
statement.close();
}
if (connection!=null){
connection.close();
}
}
}

注意:这个JdbcUtils工具类需要放在调用它的类的同一个包下

db.properties

1
2
3
4
5
driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/demo?useUnicode=true&characterEnconding=utf8&useSSL=true
username=dwx
password=123456

注意:这个配置需要放在src目录下

操作实例

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
27
28
29
30
package com.dwx.jabcstudy;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class JDBCSecond {
public static void main(String[] args) throws Exception {
Connection connection = null;
Statement statement = null;
ResultSet resultSet = null;
try {
connection = JdbcUtils.getConnection();//获取数据库链接
statement = connection.createStatement();//获得sql的执行对象
String sql = "INSERT INTO dwx(id,`name`,`sex`)" +
"VALUES(6,'kti','m')"; //有了sql命令
int i = statement.executeUpdate(sql);//将sql丢到sql执行对象里边就行了
if(i>0){
System.out.println("插入成功!!!");
}
} catch (Exception e) {
e.printStackTrace();
}finally {
JdbcUtils.release(connection,statement,resultSet); //调用工具类来释放资源
}

}
}

Donate
  • Copyright: Copyright is owned by the author. For commercial reprints, please contact the author for authorization. For non-commercial reprints, please indicate the source.

扫一扫,分享到微信

微信分享二维码
  • Copyrights © 2015-2023 dwx
  • Visitors: | Views:

请我喝杯咖啡吧~

支付宝
微信