JDBC连接数据库工具类:
package it.cast;
import java.io.FileReader;
import java.io.IOException;
import java.net.URL;
import java.sql.*;
import java.util.Properties;
public class JDBCUTILS {
private static String url;
private static String user;
private static String password;
private static String driver;
static {
try {
Properties pro = new Properties();
ClassLoader classLoader = JDBCUTILS.class.getClassLoader();
URL res = classLoader.getResource("jdbc.properties");
String path = res.getPath();
pro.load(new FileReader(path));
url = pro.getProperty("url");
user = pro.getProperty("user");
password = pro.getProperty("password");
driver = pro.getProperty("driver");
try {
Class.forName(driver);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}
}
public static Connection getConnection() throws SQLException {
return DriverManager.getConnection(url, user, password);
}
public static void close(Statement stmt, Connection conn) {
if (stmt != null) {
try {
stmt.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
public static void close(Statement stmt, Connection conn, ResultSet rs) {
if (rs != null) {
try {
rs.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if (stmt != null) {
try {
stmt.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
}
配置文件(jdbc.properties)内容:
url=jdbc:mysql://localhost:3306/db1
user=root
password=root
driver=com.mysql.jdbc.Driver
测试代码:
package it.cast;
import java.sql.*;
public class jdbc_3 {
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
ResultSet rs=null;
try {
conn = JDBCUTILS.getConnection();
String sql = "select * from account";
stmt = conn.createStatement();
rs = stmt.executeQuery(sql);
while(rs.next()){
int id = rs.getInt("id");
int balance = rs.getInt("balance");
System.out.println(id+" "+balance);
}
}catch (SQLException throwables) {
throwables.printStackTrace();
} finally {
JDBCUTILS.close(stmt,conn,rs);
}
}
}