簡體   English   中英

使用Java從SQL表獲取主鍵值

[英]Get the primary key value from SQL table using java

我正在使用Java將用戶插入sql數據庫表。 插入效果很好。 但是,用戶ID是主鍵,並且會自動遞增。 將新用戶插入表后,我想獲取用戶ID的值。

這是插入部分:

PreparedStatement create_statement;
StringBuilder sb = new StringBuilder();
sb.append("INSERT INTO ");
sb.append(this.get_database());
sb.append(".dbo.");
sb.append(this.get_table());
sb.append(" ( username, password, email_addr, first_name, middle_name, last_name, dob, street_addr, phone_num, bio)   ");
sb.append(" VALUES( ? , ? , ? , ? , ? , ? , ? , ? , ? , ? );");

try {
    create_statement = this.sql_connection.prepareStatement(sb.toString());
    create_statement.setString(1, this.username);
    create_statement.setString(2, this.password);
    create_statement.setString(3, this.email_addr);
    create_statement.setString(4, this.first_name);
    create_statement.setString(5, this.middle_name);
    create_statement.setString(6, this.last_name);
    create_statement.setString(7, this.dob);
    create_statement.setString(8, this.street_addr);
    create_statement.setString(9, this.phone_num);
    create_statement.setString(10, this.bio);
    create_statement.executeUpdate();

我正在尋找一個小時的答案,有些是通過使用ResultSet來完成的 但是,嘗試從create_statement獲取數據時,我總是收到錯誤消息或為null

救命 :(

在此處比較executeQuery和executeUpdate:

http://docs.oracle.com/javase/1.4.2/docs/api/java/sql/PreparedStatement.html

您不會從executeUpdate獲得ResultSet,因為它返回一個int。 您也不能在此處使用executeQuery,因為您要插入,而不是選擇任何內容。 改用這個

create_statement = this.sql_connection.prepareStatement(sb.toString(),
                   Statement.RETURN_GENERATED_KEYS);
//your code
ResultSet res = create_statement.getGeneratedKeys();

即使在學習時,變量也應適當命名,這不是create語句,對嗎?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM