我使用MySQL 5.x而且我不知道为什么auto_increment不起作用。我在AddressInformation中将addressID设置为Primary Key,在PersonalInformation中将addressID设置为AddressInformation的addressID的外键。这是原因吗?当我通过Workbench更新它时,它正在工作但是当我通过JDBC更新它时,它不起作用。它抛出并且参数索引超出范围错误。这是两个表的代码
CREATE TABLE PersonalInformation (
Username VARCHAR(50) NOT NULL,
Lastname VARCHAR(50),
Firstname VARCHAR(50),
Middlename VARCHAR(50),
Gender CHAR(1),
Birthdate VARCHAR(50),
AddressID INT NOT NULL,
Email VARCHAR(50),
PhoneNumber VARCHAR(50),
PRIMARY KEY ( Username )
);
CREATE TABLE AddressInformation (
AddressID INT NOT NULL AUTO_INCREMENT,
Country VARCHAR(50),
ZipCode VARCHAR(50),
State VARCHAR(50),
City VARCHAR(50),
Street VARCHAR(50),
HouseNumber VARCHAR(50),
PRIMARY KEY ( AddressID )
);
ALTER TABLE PersonalInformation ADD CONSTRAINT PersonalInformation_fk1 FOREIGN KEY ( AddressID ) REFERENCES AddressInformation( AddressID );
我的servlet中的代码:
private void toDatabase(PersonalBean p)
{
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/FoundationSystem","root","!Qaz2wsx");
PreparedStatement stmt1;
stmt1 = con.prepareStatement("INSERT INTO AddressInformation (Country, ZipCode, State, City, Street, HomeNumber) VALUES (?,?,?,?,?,?)");
stmt1.setString(2, "TestCountry");
stmt1.setString(3, p.getFirstName());
stmt1.setString(4, "TestState");
stmt1.setString(5, "TestCity");
stmt1.setString(6, "TestStreet");
stmt1.setString(7, "TestHouse");
stmt1.executeUpdate();
}
catch (Exception e)
{
System.out.println(e);
}
}
答案 0 :(得分:2)
如果我的意见一切都好。看这个
答案 1 :(得分:1)
INT的默认大小为11,这就是PersonalInformation中的内容:
AddressID INT NOT NULL
但是你的AddressInformation表中指定了15个:
AddressID INT(15) NOT NULL AUTO_INCREMENT
是的,我同意这种关系导致功能障碍。
将PersonalInformation调整为15,然后重试。