简体   繁体   English

JAVA JDBC:为 ID 列生成的键在表记录中返回 null

[英]JAVA JDBC: generated keys for ID-Column give back null in table record

I am new to Java and above all to Java JDBC.我是 Java 的新手,尤其是 Java JDBC 的新手。 I am trying to develop a simple DAO-Implementation for a GUI, in which fields from a panel get filled out and the datas get stored in an Oracle DB table named EventList.我正在尝试为 GUI 开发一个简单的 DAO 实现,其中面板中的字段被填写,数据存储在名为 EventList 的 Oracle 数据库表中。 At the moment it works with all the field of the class Event (Model) with the exception of the EventID column.目前,它适用于 class 事件(模型)的所有字段,但 EventID 列除外。 I am trying to generate an auto-increment integer through the statement GENERATED KEYS but, even though I tried different ways to reorganize the "INSERT" query in the method saveData2(), the record remains null and no keys are generated.我正在尝试通过语句 GENERATED KEYS 生成自动增量 integer 但是,即使我尝试了不同的方法在方法 saveData2() 中重新组织“INSERT”查询,记录仍然是 null 并且没有生成密钥。 What I am doing wrong?我做错了什么? Every hint would be really appreciated!每一个提示都会非常感激!

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;

public class EventDAOImpl implements EventDAO {

    @Override
    public void saveData2(Event event) {
        OracleDsSingleton ora =   OracleDsSingleton.getInstance();
        int primKey = 0;
        try {
            Connection connection = ora.getConnection();
            String addQuery = "INSERT INTO EventList(EventName, EventPlace, EventDate, EventDescription, EventCategory) VALUES (?,?,?,?,?)";
            //PreparedStatement ptmt = connection.prepareStatement(addQuery, Statement.RETURN_GENERATED_KEYS); 
//          ResultSet generatedKey = ptmt.getGeneratedKeys();
//                      if (generatedKey.next()) {
//              int key = generatedKey.getInt(1);
//              System.out.println(key);
//            }
            String columnNames [] = new String [] {"EventId"};
            
            PreparedStatement ptmt = connection.prepareStatement(addQuery, columnNames);
            
            ptmt.setString(1, event.getName());
            ptmt.setString(2, event.getPlace());
            ptmt.setString(3, event.getDate());
            ptmt.setString(4, event.getDescription());
            ptmt.setString(5, event.getCategory());
            
            //ptmt.executeUpdate();
                        
            if(ptmt.executeUpdate() > 0) {
                java.sql.ResultSet generatedKey = ptmt.getGeneratedKeys();
                if (generatedKey.next() ) {
                    event.setEventID(generatedKey.getInt(1));
                }
            }
            System.out.println("Data successfully added!");
            //System.out.println("Table updated with EventID = " + primKey);
            System.out.println(event.getName());
            
            
        } catch (SQLException e) {
            e.printStackTrace();
        }
        
    }
}

GUI面板

EventList 表模式

存储的数据

Most things in the JDBC standard are optional. JDBC 标准中的大多数内容都是可选的。 DBs are free to return nothing for .getGeneratedKeys() . DB 可以自由地为.getGeneratedKeys()不返回任何内容。 Even when you ask for them.即使你要求他们。 But you didn't, so, there's hope!但你没有,所以,有希望!

Try con.prepareStatement("SQL HERE", Statement.RETURN_GENERATED_KEYS) first.首先尝试con.prepareStatement("SQL HERE", Statement.RETURN_GENERATED_KEYS) But, if that doesn't work, you're in for a lot more effort.但是,如果这不起作用,您将付出更多努力。 Run a query to fetch the next value from the sequence (and figuring out the name of that sequence in order to do this can be quite a job,).运行查询以从序列中获取下一个值(并找出该序列的名称以便执行此操作可能是一项艰巨的工作)。 then insert that explicitly.然后明确插入。 Let's hope it doesn't need to come to this.让我们希望它不需要走到这一步。

NB: Modern DB design generally ditches the concept of an auto-count ID because keeping that counter 'in sync' with replicated servers and all that jazz is a giant headache.注意:现代 DB 设计通常抛弃自动计数 ID 的概念,因为保持该计数器与复制的服务器“同步”以及所有这些爵士乐都是一个令人头疼的问题。 If you're still at the beginning phases of all this, why not follow modern conventions?如果您仍处于这一切的开始阶段,为什么不遵循现代惯例呢? Make the ID a UUID, and just let java generate it.将 ID 设为 UUID,然后让 java 生成它。 They are no longer consecutive values, instead, they are long randomly generated strings (and with enough bits that even trillions if inserts still have less chance of a collision than you winning the lottery without buying a ticket whilst getting struck by 2 separate meteors, and lightning, all at once).它们不再是连续的值,相反,它们是随机生成的长字符串(并且有足够的位,即使插入数万亿,如果插入仍然比您在被 2 个单独的流星撞击时不买彩票而中奖的可能性要小,并且闪电,一下子)。

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

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