您的位置:首页 > 其它

JDBC 查询语句参数

2018-03-21 09:33 162 查看
如果在一个表中有很多的字段,而我们需要查询这张表中的太多数字段。这样,我们就需要写出很多的占位符。那么可以使用循环语句。public class DBHelper {
// 创建连接对象
Connection conn = null;
// 创建PreparedStatement对象
PreparedStatement pstmt = null;
// 创建结果集ResultSet
ResultSet rs = null;
// 数据库驱动
public final static String DRIVER = "com.mysql.jdbc.Driver";
// url
public final static String URL = "jdbc:mysql://localhost:3306/demo_test";
// 数据库用户名
public final static String DBNAME = "root";
// 数据库密码
public final static String DBPASS = "root";

/**
* 获取数据库连接
*
* @return
* @throws ClassNotFoundException
* @throws SQLException
* Connection
*/
public Connection getConn() throws ClassNotFoundException, SQLException {
try {
// 注册驱动
Class.forName(DRIVER);
// 获得数据库连接
conn = DriverManager.getConnection(URL, DBNAME, DBPASS);
} catch (Exception e) {
e.printStackTrace();
}
// 返回连接
return conn;
}

/**
* 释放资源
*
* @param conn
* 数据库连接
* @param pstmt
* PreparedStatement对象
* @param rs
* 结果集
*/
public void closeAll(Connection conn, PreparedStatement pstmt, ResultSet rs) {

/* 如果rs不空,关闭rs */
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
/* 如果pstmt不空,关闭pstmt */
if (pstmt != null) {
try {
pstmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
/* 如果conn不空,关闭conn */
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}

/**
* 查询
*
* @param sql
* 预编译的 SQL 语句
* @param param
* 预编译的 SQL 语句中的‘?’参数的字符串数组
* @return 影响的条数
*/
public ResultSet executeQuerySQL(String preparedSql, Object[] param) {

/* 处理SQL,执行SQL */
try {
// 得到数据库连接
conn = getConn();
// 得到PreparedStatement对象
pstmt = conn.prepareStatement(preparedSql);//执行sql语句
if (param != null) {
for (int i = 0; i < param.length; i++) {
// 为预编译sql设置参数
pstmt.setObject(i + 1, param[i]);
}
}
// 执行SQL语句,获取结果集ResultSet
rs = pstmt.executeQuery();
} catch (ClassNotFoundException e) {
// 处理ClassNotFoundException异常
e.printStackTrace();
} catch (SQLException e) {
// 处理SQLException异常
e.printStackTrace();
}
return rs;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐