简体   繁体   English

JDBC插入查询不会在数据库中插入记录

[英]JDBC insert query does not insert record in database

I have a little problem.我有一个小问题。 My database doesn't work and I don't know why.. There's no error.我的数据库不起作用,我不知道为什么.. 没有错误。 Everything looks fine, im typing values and my web app says "saved into database" it's not true.一切看起来都很好,我正在输入值,我的网络应用程序说“保存到数据库中”这不是真的。 Database is empty.数据库为空。 Here's my code:这是我的代码:

public class ConnectionManager {

    private static String dbURL = "jdbc:derby://localhost:1527/CarRental";
    private static Connection conn = null;
    private static Statement stmt = null;

    public void createConnection() {
        try {
            Class.forName("org.apache.derby.jdbc.ClientDriver").newInstance();
            conn = DriverManager.getConnection(dbURL,"GioRgio","12345");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    public void addClient(Klienci klienci) {

        String query = "INSERT INTO KLIENCI"
                + "(ID, IMIE, NAZWISKO, ADRES, TELEFON, MAIL)"
                + " VALUES (" + klienci.getId_klienta() + ",'" + klienci.getImie() + "','" 
                + klienci.getNazwisko() + "'," + klienci.getAdres()+"',"+klienci.getTelefon()+"',"+klienci.getMail() + ")"; 

        try {
            stmt = conn.createStatement();
            stmt.executeUpdate(query);
            stmt.close();
        } catch (SQLException sqlExcept) {
            sqlExcept.printStackTrace();
        }
    }
    public void closeConnection() {
        try {
            if (stmt != null) {
                stmt.close();
            }
            if (conn != null) {
                DriverManager.getConnection(dbURL + ";shutdown=true");
                conn.close();
            }
        } catch (SQLException sqlExcept) {
        }

    }
}

The immediate cause of the problem seems to be an incorrectly escaped literal in the INSERT statement (the address). 问题的直接原因似乎是INSERT语句(地址)中的文本错误转义。 We could try to fix that, but it would be much better to use a prepared statement, which handles the escaping itself. 我们可以尝试解决这个问题,但是使用准备好的语句来处理转义本身会好得多。

String sql = "INSERT INTO KLIENCI (ID, IMIE, NAZWISKO, ADRES, TELEFON, MAIL) ";
sql += "VALUES (?, ?, ?, ?, ?, ?,)";
PreparedStatement ps = conn.prepareStatement(sql);
ps.setInt(1, klienci.getId_klienta());
ps.setString(2, klienci.getImie());
ps.setString(3, klienci.getNazwisko());
ps.setString(4, klienci.getAdres());
ps.setString(5, klienci.getTelefon());
ps.setString(6, klienci.getEmail());

ps.executeUpdate();

The Answer by Tim Biegeleisen is correct about mistyping your SQL text and about the advice to use a prepared statement. 关于错误输入SQL文本以及使用准备语句的建议,Tim Biegeleisen回答是正确的。

Example app 示例应用

In support of his Answer, here is a complete example app. 为了支持他的答案,这是一个完整的示例应用程序。 Using H2 Database Engine rather than Derby . 使用H2数据库引擎而不是Derby

package com.basilbourque.example;

import java.sql.*;
import java.util.UUID;

public class CustomerDbEx {

    public static void main ( String[] args ) {
        CustomerDbEx app = new CustomerDbEx();
        app.doIt();
    }

    private void doIt ( ) {

        try {
            Class.forName( "org.h2.Driver" );
        } catch ( ClassNotFoundException e ) {
            e.printStackTrace();
        }

        try (
                Connection conn = DriverManager.getConnection( "jdbc:h2:mem:customer_example_db;DB_CLOSE_DELAY=-1" ) ; // Set `DB_CLOSE_DELAY` to `-1` to keep in-memory database in existence after connection closes.
                Statement stmt = conn.createStatement() ;
        ) {
            String sql = "CREATE TABLE customer_ ( \n" +
                    "  id_ UUID NOT NULL PRIMARY KEY , \n" +
                    "  given_name_ VARCHAR NOT NULL , \n" +
                    "  surname_ VARCHAR NOT NULL , \n" +
                    "  address_ VARCHAR NOT NULL , \n" +
                    "  phone_ VARCHAR NOT NULL , \n" +
                    "  email_ VARCHAR NOT NULL \n" +
                    ");";
            stmt.execute( sql );

            // Insert rows.
            sql = "INSERT INTO customer_ ( id_ , given_name_ , surname_ , address_ , phone_ , email_ ) \n";
            sql += "VALUES ( ? , ? , ? ,  ? , ? , ?  ) \n";
            sql += ";";
            try (
                    PreparedStatement preparedStatement = conn.prepareStatement( sql ) ;
            ) {
//                preparedStatement.setObject( 1 , customer.getId() );
//                preparedStatement.setString( 2 , customer.getGivenName() );
//                preparedStatement.setString( 3 , customer.getSurname() );
//                preparedStatement.setString( 3 , customer.getAddress() );
//                preparedStatement.setString( 3 , customer.getPhone() );
//                preparedStatement.setString( 3 , customer.getEmail() );
//                preparedStatement.executeUpdate();

                preparedStatement.setObject( 1 , UUID.fromString( "ddbf2754-f9aa-4ec3-98e9-b03da4aa83d1" ) );
                preparedStatement.setString( 2 , "Wendy" );
                preparedStatement.setString( 3 , "Melvoin" );
                preparedStatement.setString( 4 , "101 Main ST" );
                preparedStatement.setString( 5 , "(525) 555-1911" );
                preparedStatement.setString( 6 , "wendy@example.com" );
                preparedStatement.executeUpdate();

                preparedStatement.setObject( 1 , UUID.fromString( "5851c90a-f1cb-4706-a329-c54890e4d190" ) );
                preparedStatement.setString( 2 , "Lisa" );
                preparedStatement.setString( 3 , "Coleman" );
                preparedStatement.setString( 4 , "787 Dream ST" );
                preparedStatement.setString( 5 , "(525) 555-7824" );
                preparedStatement.setString( 6 , "lisa@example.com" );
                preparedStatement.executeUpdate();


            }

            // Query all.
            sql = "SELECT * FROM customer_ ;";
            try ( ResultSet rs = stmt.executeQuery( sql ) ; ) {
                while ( rs.next() ) {
                    //Retrieve by column name
                    UUID id = rs.getObject( "id_" , UUID.class );
                    String givenName = rs.getString( "given_name_" );
                    String surname = rs.getString( "surname_" );
                    String address = rs.getString( "address_" );
                    String phone = rs.getString( "phone_" );
                    String email = rs.getString( "email_" );

                    System.out.println( "Customer: " + id + " | " + givenName + " | " + surname + " | " + address + " | " + phone + " | " + email );

                    // Instantiate a `Customer` object for this data.
//                    Customer c = new Customer( id , givenName , surname , address , phone , email );
                }
            }
        } catch ( SQLException e ) {
            e.printStackTrace();
        }

    }

}

When run. 跑步时

Customer: ddbf2754-f9aa-4ec3-98e9-b03da4aa83d1 | 客户:ddbf2754-f9aa-4ec3-98e9-b03da4aa83d1 | Wendy | 温迪| Melvoin | Melvoin | 101 Main ST | 101主ST | (525) 555-1911 | (525)555-1911 | wendy@example.com wendy@example.com

Customer: 5851c90a-f1cb-4706-a329-c54890e4d190 | 客户:5851c90a-f1cb-4706-a329-c54890e4d190 | Lisa | 丽莎| Coleman | 科尔曼| 787 Dream ST | 787 Dream ST | (525) 555-7824 | (525)555-7824 | lisa@example.com lisa@example.com

即使所有语法都正确,我也遇到了这个问题,我只是缺少commit()语句

getConnection().commit();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM