url=jdbc:mysql://localhost:3306/mydb
user=root
password=ss
driver=com.mysql.jdbc.Driver
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 {
Properties pro = new Properties();
try {
ClassLoader classLoader = JDBCUtils.class.getClassLoader();
URL res = classLoader.getResource("jdbc.properties");
String path = java.net.URLDecoder.decode(res.getPath(),"utf-8");
pro.load(new FileReader(path));
url = pro.getProperty("url");
user = pro.getProperty("user");
password = pro.getProperty("password");
driver = pro.getProperty("driver");
Class.forName(driver);
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException 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(ResultSet rs, Statement stmt, Connection conn){
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();
}
}
}
}
import jdk.nashorn.internal.scripts.JD;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class JDBCUtilsDemo {
Connection conn= null;
Statement stmt = null;
ResultSet rs = null;
public static void main(String[] args) {
new JDBCUtilsDemo().test();
}
public void test(){
try {
conn = JDBCUtils.getConnection();
String sql = "select * from t_user";
stmt = conn.createStatement();
rs = stmt.executeQuery(sql);
while (rs.next()){
String user_name = rs.getString("user_name");
System.out.println(user_name);
}
} catch (SQLException throwables) {
throwables.printStackTrace();
} finally {
JDBCUtils.close(rs,stmt,conn);
}
}
}