什么时候自己创建工具类
如果一个功能经常用到 我们建议把这个功能做成工具类
创建JdbcUtils包含三个方法1: 把几个字符串 定义为常量2:得到数据库连接getConnection();3关闭和打开资源packageJdbcUtils;import java.sql.*;public classJdbcUtilsDemo {public static final String USER = "root";public static final String PSW = "root";public static final String URL = "jdbc:mysql://localhost:3306/qy97";public static final String DRIVER = "com.mysql.jdbc.Driver";static{try{
Class.forName(DRIVER);
}catch(ClassNotFoundException e) {
e.printStackTrace();
}
}public static Connection getConnection() throwsSQLException {returnDriverManager.getConnection(URL,USER,PSW);
}/*public static void close(Statement st,Connection con){
if (st!=null){
try {
st.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(con!=null){
try {
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
public static void close(Connection con, Statement st, ResultSet rs){
if(rs!=null){
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (st!=null){
try {
st.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (con!=null){
try {
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}*/
public static voidclose(AutoCloseable... ca){for(AutoCloseable c:ca){if(c!=null){try{
c.close();
}catch(Exception e) {
e.printStackTrace();
}
}
}
}
}
调用工具类方法进行查询packagecn.lideng.dbc;importJdbcUtils.JdbcUtilsDemo;importjava.sql.Connection;importjava.sql.ResultSet;importjava.sql.SQLException;importjava.sql.Statement;public classJdbcDemo5 {private staticConnection connection;private staticStatement statement;private staticResultSet rs;public static voidmain(String[] args){try{
connection=JdbcUtilsDemo.getConnection();
String sql="select * from users";
statement=connection.createStatement();
rs=statement.executeQuery(sql);while(rs.next()){int id = rs.getInt(1);
String name= rs.getString(2);
String address= rs.getString(3);
System.out.println(id+" "+name+" "+address);
}
}catch(SQLException e) {
e.printStackTrace();
}finally{
JdbcUtilsDemo.close(rs,statement,connection);
}
}
}