JDBC工具类封装
1、创建jdbc.properties配置文件
url=jdbc:mysql:/
user:root
password=0211
driver=com.mysql.cj.jdbc.Driver
2、工具类
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();
System.out.println(path);
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(ResultSet rs, Statement stmt, Connection conn){
if(rs !=null){
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(stmt !=null){
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(conn != null){
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
3、利用工具类对数据查询
package com.Jdbctest;
import jdbcutils.JDBCutils;
import java.sql.*;
public class jdbcquery2 {
public static void main(String[] args) throws Exception {
Statement stmt = null;
Connection conn =null;
ResultSet count = null;
try {
conn=JDBCutils.getConnection();
String sql = "select *from test;";
stmt = conn.createStatement();
count = stmt.executeQuery(sql);
while(count.next()) {
int id = count.getInt(1);
String name = count.getString("name");
System.out.println(id + name);
}
} catch (SQLException E){
E.printStackTrace();
}finally {
JDBCutils.close(count,stmt,conn);
}
}
}