1

次の更新クエリが、SQLYog エディターから直接実行すると完全に機能するのに、Java からは実行しない理由を教えてください。例外はありませんが、データベースに更新されていません。

これは更新クエリです

UPDATE hotel_tables SET hotel_tables.status='reserved' WHERE hotel_tables.section='pub' AND tableno='4' AND ('4' NOT IN (SELECT tableno FROM table_orders WHERE outlet='pub'))

Java コード

public static void main(String[] args) throws Exception {
    int update = new Dbhandler().update("UPDATE hotel_tables SET hotel_tables.status='reserved' WHERE hotel_tables.section='pub' AND tableno='4' AND ('4' NOT IN (SELECT tableno FROM table_orders WHERE outlet='pub'))");
}

public int update(String Query)throws Exception
{
    try
    {
        cn=getconn();
        stmt=(Statement) cn.createStatement();
        n=stmt.executeUpdate(Query);
        stmt.close();
    }
    catch(Exception e)
    {
        e.printStackTrace();
        throw(e);
    }
    finally
    {
        cn.close();
    }
    return n;
}

public Connection getconn()
{
    try
    {
        Class.forName(driver).newInstance();
        String url="jdbc:mysql://localhost/kot?user=root&password=root";
        cn=(Connection) DriverManager.getConnection(url);
    }
    catch(Exception e)
    {
        System.out.println("DBHandler ERROR:"+e);
    }
    return cn;
}
4

2 に答える 2

0

これは、Spring の JdbcTemplate フレームワークに切り替える前に私が行っていた方法です。多分これが役立つでしょう。それはあなたのものに非常に似ています。

public static int runUpdate(String query, DataSource ds, Object... params) throws SQLException  {
    int rowsAffected = 0;
    Connection conn = null;
    PreparedStatement stmt = null;
    try {
        conn = ds.getConnection();
        stmt = conn.prepareStatement(query);
        int paramCount = 1;
        for (Object param : params) {
            stmt.setObject(paramCount++, param);
        }
        rowsAffected = stmt.executeUpdate();
        conn.commit();
    } catch (SQLException sqle) {
        throw sqle;
        //log error
    } finally {
        closeConnections(conn, stmt, null);
    }
    return rowsAffected;
}

いくつかの微妙な違いがあります。autoCommit がデフォルトですが、コミットします。

于 2013-10-29T14:19:30.943 に答える