Java之数据库连接基础
代码片段总结了Java与数据库连接的基本方法,连接SQL、MySql等只需修改相应的数据库类型和端口号,其余步骤同。数据库的基本操作包括:增、删、改、查,一应方法都有定义,需要时只需要调用相应的方法即可。
----------------------------------------------------------------------------------------------------------------------------------------------------
package cn.JJ;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ParameterMetaData;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
/**
* 查询结果处理接口
*/
interface ResultSetHander {
Object hander(ResultSet rs);
}
/**
* 类说明:数据库连接和释放
*/
public class JDBCUtils {
private static String driver = "com.mysql.jdbc.Driver";
private static String url = "jdbc:mysql://localhost:3306/chat";
private static String user = "root";
private static String password = "root";
private static Connection con = null;
// 注册驱动
static {
try {
Class.forName(driver);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
// 创建连接
public static Connection getConnection() {
if (con == null) {
try {
con = DriverManager.getConnection(url, user, password);
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
return con;
}
// 关闭连接
public static void colse(ResultSet rs, Statement st, Connection con) {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
if (st != null) {
try {
st.close();
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
if (con != null) {
try {
con.close();
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
}
// 更新数据库
public static void update(String sql, Object[] params) {
Connection con = JDBCUtils.getConnection();
Statement stmt = null;
ResultSet rs = null;
try {
PreparedStatement ps = con.prepareStatement(sql);
ParameterMetaData psm = ps.getParameterMetaData();// 获得查询语句的元数据信息
int paramNum = psm.getParameterCount();// 得到参数的总个数
for (int i = 1; i <= paramNum; i++) {
ps.setObject(i, params[i - 1]);
}
ps.executeUpdate();
} catch (SQLException e) {
throw new RuntimeException(e);
} finally {
JDBCUtils.colse(rs, stmt, con);
}
}
// 查询数据库
public static Object query(String sql, Object[] params, ResultSetHander rsh) {
Connection con = JDBCUtils.getConnection();
Statement stmt = null;
ResultSet rs = null;
try {
PreparedStatement ps = con.prepareStatement(sql);
ParameterMetaData psm = ps.getParameterMetaData();// 获得查询语句的元数据信息
int paramNum = psm.getParameterCount();// 得到参数的总个数
for (int i = 1; i <= paramNum; i++) {
ps.setObject(i, params[i - 1]);
}
rs = ps.executeQuery();
return rsh.hander(rs);
} catch (SQLException e) {
throw new RuntimeException(e);
} finally {
JDBCUtils.colse(rs, stmt, con);
}
}
}