// DB.java
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
//封装DB,增强程序维护的维护性
public class DB {
private final static String DRIVER_CLASS="com.mysql.jdbc.Driver"; //驱动类路径
private final static String URL="jdbc:mysql://127.0.0.1:3306/test"; //连接字符串
private final static String USER="root"; //数据库用户名
private final static String PASSWORD="root"; //数据库密码
//获得连接Connection
public static Connection getConnection() {
Connection conn = null;
try {
Class.forName(DRIVER_CLASS);
//建立连接
conn = DriverManager.getConnection(URL,USER,PASSWORD);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return conn;
}
//获得语句对象Statement
public static Statement getStatement(Connection conn) {
Statement stmt = null;
try {
if(conn != null) {
stmt = conn.createStatement();
}
} catch (SQLException e) {
e.printStackTrace();
}
return stmt;
}
//获得语句对象PreparedStatement
public static PreparedStatement getPreparedStatement(Connection conn,String sql) {
PreparedStatement ps = null;
try {
if(conn != null) {
ps = conn.prepareStatement(sql);
}
} catch (SQLException e) {
e.printStackTrace();
}
return ps;
}
//获得结果集ResultSet
public static ResultSet getResultSet(Statement stmt, String sql) {
ResultSet rs = null;
try {
if(stmt != null) {
rs = stmt.executeQuery(sql);
}
} catch (SQLException e) {
e.printStackTrace();
}
return rs;
}
//获得结果集ResultSet
public static int getResultInt(Statement stmt, String sql) {
int cnt = 0;
try {
if(stmt != null) {
cnt = stmt.executeUpdate(sql);
}
} catch (SQLException e) {
e.printStackTrace();
}
return cnt;
}
//关闭连接
public static void closeConnection(Connection conn) {
try {
if(conn != null) {
conn.close();
conn = null;
}
} catch (SQLException e) {
e.printStackTrace();
}
}
//关闭语句对象Statement
public static void closeStatement(Statement stmt) {
try {
if(stmt != null) {
stmt.close();
stmt = null;
}
} catch (SQLException e) {
e.printStackTrace();
}
}
//关闭结果集ResultSet
public static void closeResultSet(ResultSet rs) {
try {
if(rs != null) {
rs.close();
rs = null;
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
//Test.java
class Test{
public static void main(String args []){
DB.getConnection();
}
}