我正在学习如何在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 void closeDatabase()
{
try
{
stmt.close();
c.close();
}
catch (Exception e)
{
System.err.println(e.getClass().getName() + ": " + e.getMessage());
System.exit(0);
}
System.out.println("Database closed successfully");
}
Run Code Online (Sandbox Code Playgroud)
虽然没有进行任何数据库更改,但控制台中的结果如下:
数据库成功打开
1
数据库成功关闭
提前致谢!
c.setAutoCommit(false)从openDatabase方法中删除行.
要么
c.commit()在updateSchool方法的最后添加.
禁用自动提交模式后,在显式调用方法提交之前,不会提交任何SQL语句.在上一次调用方法提交之后执行的所有语句都包含在当前事务中,并作为一个单元一起提交.