How to auto increment database column in Java derby?

ⅰ亾dé卋堺 提交于 2021-01-27 18:23:23

问题


Here's the SQL I've tried so far to create the table

CREATE TABLE tblPosts (nId INTEGER PRIMARY KEY GENERATED ALWAYS AS IDENTITY,
strContent VARCHAR(140) NOT NULL,
strLink VARCHAR(200),
strImage VARCHAR(200));

using

String sql = "INSERT INTO tblPosts VALUES ('" + textFieldContent.getText() + "', '" + 

textFieldLink.getText() + "', '" + textFieldImage.getText() + "')";

I get an error telling me I'm not providing the nId column value which I'm not but if the column auto-increments I'm not supposed to right?

I've also tried using the IDE to create the table on the database as described here

Alter a table column with auto increment by 1 in derby

Same response though. Any suggestions?


回答1:


I would guess that since you're not specifying the column names in the SELECT, it is getting confused as to which columns the data should go in. I would specify the column names in your INSERT command.




回答2:


You need to include Start with 1, Increment by 1 Like this

CREATE TABLE tblPosts (nId INTEGER PRIMARY KEY GENERATED ALWAYS AS IDENTITY(Start with 1, Increment by 1), 
strContent VARCHAR(140) NOT NULL, 
strLink VARCHAR(200)



回答3:


You need to set THAT auto_increment column to DEFAULT like this:

String sql = "INSERT INTO tblPosts VALUES ( DEFAULT, '" + textFieldContent.getText() + "', '" + 

textFieldLink.getText() + "', '" + textFieldImage.getText() + "')";


来源:https://stackoverflow.com/questions/42302541/how-to-auto-increment-database-column-in-java-derby

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!