📄 sqlcommandbean.java
字号:
package Dao;
import java.util.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.jsp.jstl.sql.Result;
import javax.servlet.jsp.jstl.sql.ResultSupport;
public class SQLCommandBean {
private Connection conn;
private String sqlValue;
private List values;
//设定连接类
public void setConn(Connection conn) {
this.conn = conn;
}
//设定SQL语句
public void setSqlValue(String sqlValue) {
this.sqlValue = sqlValue;
}
//设定SQL语句的参数
public void setValues(List values) {
this.values = values;
}
//执行语句
public Result executeQuery()throws Exception
{
Result result = null;
ResultSet rs = null;
PreparedStatement pst = null;
Statement st = null;
try
{
if(values != null && values.size() > 0)
{
pst = conn.prepareStatement(this.sqlValue);
setValues(pst,values);
rs = pst.executeQuery();
}
else
{
st = conn.createStatement();
rs = st.executeQuery(this.sqlValue);
}
result = ResultSupport.toResult(rs);
}
finally
{
try
{
if(rs != null)
{
rs.close();
}
if(st != null)
{
st.close();
}
if(pst != null)
{
pst.close();
}
}catch(Exception ex)
{
System.out.println("查询语句出错");
ex.printStackTrace();
}
}
return result;
}
//执行Update语句
public int executeUpdate() throws Exception
{
int noOfRows = 0;
ResultSet rs = null;
PreparedStatement pst = null;
Statement st = null;
try
{
if(values != null && values.size() > 0)
{
pst = conn.prepareStatement(sqlValue);
setValues(pst,values);
noOfRows = pst.executeUpdate();
}
else
{
st = conn.createStatement();
noOfRows = st.executeUpdate(this.sqlValue);
}
}finally
{
try
{
if(rs != null)
{
rs.close();
}
if(st != null)
{
st.close();
}
if(pst != null)
{
pst.close();
}
}catch(Exception ex)
{
ex.printStackTrace();
}
}
return noOfRows;
}
//设定语句参数的方法
private void setValues(PreparedStatement pst,List values)throws Exception
{
for(int i = 0; i< values.size(); i ++)
{
Object v = values.get(i);
pst.setObject(i+1,v);
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -