在src文件夹下创建配置文件 db.properties
db.properties
drivername=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/mydb
user=root
password=root
JDBCUtil.java
package com.gordon.jdbcutil;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;
public class JDBCUtil {
public static String DRIVERNAME = null;
public static String URL = null;
public static String USER = null;
public static String PASSWORD = null;
public static Connection conn = null;
static {
try {
Properties props = new Properties();
//Reader in = new FileReader("db.properties");
InputStream in = JDBCUtil.class.getClassLoader().getResourceAsStream("db.properties");
props.load(in);
DRIVERNAME = props.getProperty("drivername");
URL = props.getProperty("url");
USER = props.getProperty("user");
PASSWORD = props.getProperty("password");
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static Connection getConnection() throws Exception {
if (conn != null) {
return conn;
}
Class.forName(DRIVERNAME);
conn = DriverManager.getConnection(URL, USER, PASSWORD);
return conn;
}
public static void closeResource(Connection conn, PreparedStatement st) throws SQLException {
st.close();
conn.close();
}
public static void closeResource(Connection conn, ResultSet rs, PreparedStatement st) throws SQLException {
st.close();
rs.close();
conn.close();
}
}
* 注意其中的获取配置文件的代码。
jdbc01.java测试文件
package com.gordon.jdbc;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import com.gordon.jdbcutil.JDBCUtil;
public class jdbc01 {
public static void main(String[] args) {
selectFunction();
}
public static void selectFunction() {
try {
//1.获取连接
Connection conn = JDBCUtil.getConnection();
// 3.sql语句
String sql = "SELECT * FROM user";
// 3.获取SQL执行者
PreparedStatement st = conn.prepareStatement(sql);
// 4.设置参数
// 5.执行sql语句
ResultSet rs = st.executeQuery();
// 6.处理数据
while (rs.next()) {
System.out.println(rs.getString("id") + ":" + rs.getString("name"));
}
// 7.释放资源
JDBCUtil.closeResource(conn, rs, st);
} catch (SQLException ex) {
System.out.println(ex.getMessage());
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}