我正在尝试使用以下查询注册用户:
"INSERT INTO Users (Username, Password, FirstName, Surname, Age, HouseNumber,
StreetName, Town, County, Postcode, TelephoneNumber,
isBanned, isAdmin)
VALUES ('" + textboxUsername.Text + "','" + textboxPassword.Text + "','" +
textboxFirstName.Text + "','" + textboxSurname.Text + "','" + textboxAge.Text + "','" + textboxHouseNumber.Text +
"','" + textboxStreetName.Text + "','" +
textboxTown.Text + "','" + textboxCounty.Text + "','" +
textboxPostcode.Text + "','" + textboxTelephoneNumber.Text +
"', 'false', 'false')", con);
数据库按照您的预期设置,只有上述值和UserID,它应该是使用Identity Specification的自动增量值。但是,我收到以下错误:
Cannot insert the value NULL into column 'UserID', table 'myFilePath'; column does not allow nulls. INSERT fails.
这是为什么?我无法告诉它为UserID插入任何内容,因为数据库需要处理它,目前UserID是主键,因此不能为null。我究竟做错了什么?这曾经在几个月前工作
答案 0 :(得分:2)
确保您的列上有序列,如果没有添加一个序列:
CREATE SEQUENCE yourschemaname.Users
START WITH 1
INCREMENT BY 1;
GO
答案 1 :(得分:2)
您还可以在查询中提及id
为NULL
。它将使用auto-increment
填充:
INSERT INTO Users
(UserID, Username, Password, FirstName, Surname, Age, HouseNumber, StreetName,
Town, County, Postcode, TelephoneNumber, isBanned, isAdmin
)
VALUES
(NULL,'" + textboxUsername.Text + "','" +
textboxPassword.Text + "','" + textboxFirstName.Text + "','" +
textboxSurname.Text + "','" + textboxAge.Text + "','" + textboxHouseNumber.Text + "','" +
textboxStreetName.Text + "','" + textboxTown.Text + "','" + textboxCounty.Text + "','" +
textboxPostcode.Text + "','" + textboxTelephoneNumber.Text + "', 'false', 'false')",
con);
同时检查字段UserID
的数据类型它应该是这样的:
UserID INT unsigned NOT NULL AUTO_INCREMENT PRIMARY KEY;
答案 2 :(得分:1)
您可以使用SQL AUTO INCREMENT:
使用AUTO_INCREMENT定义您的表:
CREATE TABLE Users
(
UserID int NOT NULL AUTO_INCREMENT,
Username varchar(255) NOT NULL,
Password varchar(255) ,
.....
PRIMARY KEY (UserID)
)
然后执行插入:
INSERT INTO Users (Username, Password, FirstName, Surname, Age, HouseNumber,
StreetName, Town, County, Postcode, TelephoneNumber,
isBanned, isAdmin)
答案 3 :(得分:1)
无法相信我必须这样做,但数据库连接路径错误。对不起,伙计,我丢了一封信。我会向所有人投票,并“回答”我自己,以便人们可以看到。