【发布时间】:2017-03-10 10:52:38
【问题描述】:
我正在学习如何在 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);
}
}
支持功能
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");
}
控制台中的结果如下,尽管没有进行数据库更改:
数据库打开成功
1
数据库关闭成功
提前致谢!
【问题讨论】:
-
不要使用“;”它可以破坏sql;你有什么例外吗?
-
你需要刷新你的数据库,或者提交
c.setAutoCommit(True); -
@karelss 来自 Postgres documentation:
Get in the habit of including those SQL semicolons -
学习“尝试资源”。
-
try(Connection con = getConnection(url, username, password, "org.postgresql.Driver"); Statement stmt = con.createStatement(); ResultSet rs = stmt.executeQuery(sql); ) { //statements }catch(....){} 在此处阅读更多信息 stackoverflow.com/questions/2225221/…