数据库问题

dudeng 2005-11-13 09:45:29
到底statement和preparedStatement 的 execute executeUpdate executeQuery 用在什么时候 有什么区别?特别是preparedStatement.
我遇到两个问题都是最后preparedStatement.execute(...);有问题。我检查了决定不是sql语句的问题。也不是我没有导入包的问题,是怎么回事啊?
...全文
127 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
dudeng 2005-11-14
  • 打赏
  • 举报
回复
zeq258:
你就应该检查你的缓存机制是否用的合适。 你能不能说清楚点点 我不懂什么意思啊
joyaga 2005-11-14
  • 打赏
  • 举报
回复
preparedStatement con.prepareStatement(sqlStr); 是预置sql语句 里面可以有可变的参数设置如,ps.setString(...);执行如 ps.executeQuery();
Statement con.createStatement(); 用于固定sql语句 执行的时候如stmt.executeQuery(sqlStr)
ljhyp_cn 2005-11-14
  • 打赏
  • 举报
回复
楼主:
statement是存语句查询
preparedStatement是参数查询,参数查询在数据库有缓存,可以提高速度.
他们的区别很大
请看
/**
* @author longjianhui Date:2005-6-8 11:12:32 tags:@param connStr
* tags:@param sqlStr tags:@return Return_Type:ResultSet
* Description:获取只读数据集
*/
public static ResultSet getResultSet(Connection connection, String sqlStr)
throws Exception {
ResultSet rs = null;
try {
if (UF.SysOutPrintFlag())
System.out.println("sql:" + sqlStr);
Statement stmt = connection.createStatement();
rs = stmt.executeQuery(sqlStr);
return rs;
} catch (SQLException ex) {
if (rs != null) {
rs.close();
rs = null;
}
throw ex;
}
}
2
/**
*
* @param connection
* @param sqlStr
* @param objArr
* @return
* @throws SQLException
* Description:根据参数语句获取只读数据集
*/
public static ResultSet getResultSet(Connection connection, String sqlStr,
Object[] objArr) throws Exception {
PreparedStatement ps = null;
try {
if (UF.SysOutPrintFlag())
System.out.println("sql:" + sqlStr);
ps = connection.prepareStatement(sqlStr);
for (int i = 1; i <= objArr.length; i++) {
Object obj = objArr[i - 1];
ps.setObject(i, objArr[i - 1]);
}
return ps.executeQuery();
} catch (SQLException ex) {
if (ps != null) {
ps.cancel();
ps.close();
ps = null;
}
throw ex;
}
}
zeq258 2005-11-14
  • 打赏
  • 举报
回复
preparedStatement 区别与statement在于它的缓存机制,

如果是最后对数据库的操作,数据有问题,但是程序却能正常运行。

你就应该检查你的缓存机制是否用的合适。
honbo 2005-11-14
  • 打赏
  • 举报
回复
把代码和执行的sql语句贴出来,
出错的报错信息也贴出来看看
ljhyp_cn 2005-11-14
  • 打赏
  • 举报
回复
采用这个ps.executeQuery();
并且你要检查你说设置的对象
和数据库的类型是否一直.
dudeng 2005-11-14
  • 打赏
  • 举报
回复
//添加商品
public void addProduct(Product product)
{
PreparedStatement pstmt = null;
try
{
pstmt = con.prepareStatement("insert into products values(?,?,?,?,?,?)");
pstmt.setString(1,product.getProductId());
pstmt.setString(2,product.getCategoryId());
pstmt.setString(3,product.getName());
pstmt.setString(4,product.getProducer());
pstmt.setFloat(5,product.getPrice());
pstmt.setString(6,product.getDescription());
}
catch(Exception ex)
{
ex.printStackTrace();
}
try
{
pstmt.execute(); //错误就在这句话???为什么?
}
catch(Exception e)
{
e.printStackTrace();
}
}

81,114

社区成员

发帖
与我相关
我的任务
社区描述
Java Web 开发
社区管理员
  • Web 开发社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧