我正在编写一个程序,我正在改变角色。Change Role过程涉及从两个表中删除(清除当前角色/组),插入到两个表中(设置角色/组)。
我allowMultipleQueries = true
在我的连接字符串,但它看起来像只有第一个查询正在运行。
该数据库是一个 MSSQL 数据库。
有没有办法运行这两个查询?我可以从两个表中删除吗?
我的代码如下:
JButton changeRoleBtn = new JButton("Change Role");
changeRoleBtn.setBounds(50, 375, 150, 30);
changeRoleBtn.setToolTipText("Changes the role of the User");
changeRoleBtn.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
if (requesterRole.isSelected())
{
StringBuffer getRolesQuery3 = new StringBuffer("delete from hib.personrole where personid = '");
getRolesQuery3.append(userID).append("'");
StringBuffer getRolesQuery4 = new StringBuffer("delete from hib.persongroup where personid = '");
getRolesQuery4.append(userID).append("'");
try
{
ResultSet rs = stmt.executeQuery(getRolesQuery3.toString());
ResultSet rs1 = stmt.executeQuery(getRolesQuery4.toString());
boolean empty = true;
if(empty)
{
userRoleLbl.setText("The User is a Requester");
System.out.println(rs);
System.out.println(rs1);
}
}
catch(Exception e2)
{
System.out.println(e2);
}
}
}
});
Run Code Online (Sandbox Code Playgroud)
我已将其更改为准备好的语句,但在运行时出现以下错误。 java.sql.SQLException: Invalid parameter index 2.
changeRoleBtn.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
if (requesterRole.isSelected())
{
try
{
PreparedStatement ps1, ps2;
ps1 = con.prepareStatement("delete from hib.personrole where personid = ?");
ps2 = con.prepareStatement("delete from hib.persongroup where personid = ?");
ps1.setInt(1, userID);
ps2.setInt(2, userID);
ps1.executeQuery();
ps2.executeQuery();
con.commit();
userRoleLbl.setText("The user is a requester");
}
catch(Exception e3)
{
e3.printStackTrace();
}
}
}
});
Run Code Online (Sandbox Code Playgroud)
我相信这里使用批处理会更合适。当您一次向数据库发送多条SQL语句时,您减少了通信开销量,从而提高了性能。
JDBC 驱动程序不需要支持此功能。您应该使用 DatabaseMetaData.supportsBatchUpdates() 方法来确定目标数据库是否支持批量更新处理。如果您的 JDBC 驱动程序支持此功能,则该方法返回 true。
示例代码
con.setAutoCommit(false);
stmt.addBatch(getRolesQuery3);
stmt.addBatch(getRolesQuery4);
ResultSet rs = stmt.executeBatch();
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
2183 次 |
最近记录: |