Java中的ExecuteUpdate SQL语句不起作用 [英] ExecuteUpdate sql statement in Java not working

查看:323
本文介绍了Java中的ExecuteUpdate SQL语句不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习如何在Java中使用SQL.我已经成功安装了JDBC驱动程序,并且能够从数据库中读取记录并将其打印在屏幕上.

I am learning how to use SQL with Java. I have installed the JDBC driver successfully and I am able to read the records from a database and print it on the screen.

我的问题在尝试执行更新或插入语句时发生,但没有任何反应.这是我的代码:

My problem occurs when trying to do either an update or insert statement, where nothing happens. Here is my code:

问题所在的方法

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");
}

这是我非常简单的数据库的图像:

Here is an image of my very simple database:

尽管未进行任何数据库更改,但控制台中的结果如下:

The result in the console is the following, although no databases changes were done:

数据库成功打开

1

数据库成功关闭

提前谢谢!

推荐答案

openDatabase方法中删除c.setAutoCommit(false)行.

updateSchool方法的末尾添加c.commit().

在禁用自动提交模式后,没有SQL语句 直到您显式调用方法commit为止.所有陈述 在上一次对方法提交的调用之后执行的操作包括在 当前的交易,并作为一个单元一起提交.

After the auto-commit mode is disabled, no SQL statements are committed until you call the method commit explicitly. All statements executed after the previous call to the method commit are included in the current transaction and committed together as a unit.

这篇关于Java中的ExecuteUpdate SQL语句不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆