我试图在accountInfo表中插入新行,但出现完整性约束错误。我已经准备好将所有内容添加到外键引用的表中,所以我想知道问题可能出在哪里。
private void createTables(){
// To be completed
String accounts = "create table accounts ( "+
" accountID integer,"+
" billingAddress VARCHAR(100),"+
" primary key(accountID)" +
")";
try {
connection.createStatement().executeUpdate(accounts);
String bills = "create table bills ("
+ " billID integer,"
+ " amount integer,"
+ " accountID integer,"
+ " primary key(billID),"
+ " foreign key (accountID) references accounts);";
connection.createStatement().executeUpdate(bills);
String viewerAccount = "create table viewerAccount ("
+ " viewerName CHAR(100),"
+ " accountID integer,"
+ " primary key(viewerName),"
+ " foreign key (accountID) references accounts)";
connection.createStatement().executeUpdate(viewerAccount);
String videos = "create table videos "
+ "(link CHAR(50),"
+ " creatorName VARCHAR(100),"
+ " videoName VARCHAR(100),"
+ " duration integer,"
+ " primary key(link))";
connection.createStatement().executeUpdate(videos);
String accountInfo = "create table accountInformation ("
+ " accountID integer,"
+ " time integer,"
+ " link CHAR(50),"
+ " primary key(accountID,time),"
+ " foreign key (accountID) references accounts,"
+ " foreign key (link) references videos)";
connection.createStatement().executeUpdate(accountInfo);
}
catch (SQLException e) {
e.printStackTrace(System.out);
}
当我尝试使用此方法从纺织品读取数据时,出现错误:
private int makeAccountInfo(String accountID, String time, String link){
int aID = -1;
try{
PreparedStatement pstmt = connection.prepareStatement(
"Select time From accountInformation where accountID = ? AND time = ?;"
);
pstmt.setInt(1, Integer.parseInt(accountID));
pstmt.setInt(2, Integer.parseInt(time));
ResultSet resultSet = pstmt.executeQuery();
if (resultSet.next()) {
// at least 1 row (hopefully one row!) exists. Get the ID
aID = resultSet.getInt("");
}
else{
// no record
// make the new account
PreparedStatement addAccountInfo = connection.prepareStatement(
"insert into accountInformation (accountID, time, link) values (?, ?, ?);"
);
addAccountInfo.setInt(1, Integer.parseInt(accountID));
addAccountInfo.setInt(2, Integer.parseInt(time));
addAccountInfo.setString(3, link);
int numUpdated= addAccountInfo.executeUpdate();
addAccountInfo.close();
resultSet.close();
}
pstmt.close();
}
catch (SQLException e) {
System.out.println("Error in " + accountID + " " + time + " " + link);
e.printStackTrace(System.out);
}
return aID;
}