JDBC工具类
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class JDBCUtil {
public static final String DB_URL = "jdbc:mysql://localhost:3306/test";
public static final String DB_NAME = "root";
public static final String DB_PWD = "";
static {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
/**
* 取得连接
*
* @return
*/
public static Connection getConnection() {
try {
return DriverManager.getConnection(DB_URL, DB_NAME, DB_PWD);
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
/**
* 释放资源
*
* @param rs
* @param stmt
* @param conn
*/
public static void free(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();
}
}
}
}
JDBC主要使用步骤:
(1)、加载驱动程序(使用 Driver 接口装载一个合适的驱动程序)
(2)、建立连接(使用 Connection 接口连接到数据库)
(3)、创建和执行语句(使用 Statement 接口创建和执行 SQL 语句)
(4)、处理结果(如果语句返回数据集结果,可以使用 ResultSet 接口处理该结果)