我试图在一个执行中执行两个插入查询Statement
,将它们放在一个事务中.
我正在查看该addBatch
方法,但如果我理解正确,它可以与单个PreparedStatement
一起使用,使用不同的参数多次执行相同的插入,或者在Statement
对象上使用以向批处理添加更多查询,但无法添加参数(所以我可能能够在sql字符串中添加值.SQL注入风格).
我也试过一种简单的方法,在一个sql语句(insert into table1 values(?, ?); insert into table2 values(?, ?);
)中编写两个插入,但是这样PreparedStatement
只能看到前两个参数,并尝试设置第三个和第四个抛出异常.
我正在学习如何在Java中使用SQL.我已经成功安装了JDBC驱动程序,我可以从数据库中读取记录并将其打印在屏幕上.
尝试执行更新或插入语句时,我的问题发生,没有任何反应.这是我的代码:
问题所在的方法
public static void updateSchools(ArrayList<String> newSchool)
{
try
{
openDatabase();
stmt = c.createStatement();
int numberOfRows = stmt.executeUpdate("UPDATE schools SET address='abc' WHERE abbreviation='2';");
System.out.println(numberOfRows);
closeDatabase();
}
catch (Exception e)
{
System.err.println(e.getClass().getName() + ": " + e.getMessage());
System.exit(0);
}
}
Run Code Online (Sandbox Code Playgroud)
支持功能
public static void openDatabase()
{
c = null;
stmt = null;
try
{
Class.forName("org.postgresql.Driver");
c = DriverManager.getConnection("jdbc:postgresql://localhost:5432/Badminton", "postgres", "postgrespass");
c.setAutoCommit(false);
}
catch (Exception e)
{
System.err.println(e.getClass().getName() + ": " + e.getMessage());
System.exit(0);
}
System.out.println("Database opened successfully");
}
public static …
Run Code Online (Sandbox Code Playgroud)