JDBC 使用和配置
/**
* 数据库工具类,封装数据库操作中多次使用的数据库操作代码
* @author Administrator
*
*/
public class DBUtils {
public static Connection getConnection() {
Connection connection = null;
try {
Class.forName("com.mysql.jdbc.Driver");
String databaseName = "jdbc_test";
String url = "jdbc:mysql://localhost:3306/" + databaseName;
String user = "root";
String password = "111";
connection = DriverManager.getConnection(url, user, password);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return connection;
}
}
*Connection connection = DBUtils.getConnection();
*PreparedStatement preparedStatement = connection.prepareStatement(sql);
*ResultSet resultSet = preparedStatement.executeQuery();
以上三个流都需要进行关闭 也都可以用try - with - resource 进行关闭 (自动关闭 不需要手动)

* jdbc.properties
url=jdbc:mysql://localhost:3306/test104
user=root
password=123456
package com.zhiyou100.util;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;
public enum DBUtils {
/*
* 单例通过枚举实现,枚举最后一个单词后以 ; 结尾
* 构造方法都是 private 修饰,不让通过 new 构造方法创建对象
* static 方法中只能使用 static 变量,不能使用类的实例变量(属性,全局变量)
*/
INSTANCE;
private String url;
private String user;
private String password;
private DBUtil() {
try {
InputStream inputStream = DBUtils.class.getClassLoader().getResourceAsStream("jdbc.properties");
Properties properties = new Properties();
properties.load(inputStream);
url = properties.getProperty("url");
user = properties.getProperty("user");
password = properties.getProperty("password");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public Connection getConnection() {
Connection conn = null;
try {
Class.forName("com.mysql.jdbc.Driver");
// 读取编译后的 class 文件夹下的某一个文件
conn = DriverManager.getConnection(url, user, password);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return conn;
}
}

浙公网安备 33010602011771号