尝试在MySQL中的数据表中添加新记录失败,并显示错误消息:
无法添加或更新子行
我可以在xampp中手动执行相同的命令,它可以正常工作,但是在我的应用程序下运行时却不能。 这是代码,从表“ users”开始,然后是“ transactions”
public void CreateUsersTable(){
try {
String SQL = "CREATE TABLE IF NOT EXISTS Users ("
+ "Username varchar(80) NOT NULL,"
+ "Userpassword varchar(80) ,"
+ "User_GSM VARCHAR(30),"
+ "User_Tel_Home VARCHAR(30),"
+ "User_Address Varchar(100), "
+ "User_City Varchar(20), "
+ "User_Position Varchar(100), "
+ "PRIMARY KEY(Username))";
//con = DBModule.ConnectDataBase.ConnectDataBase_Method();
statement = con.prepareStatement(SQL);
statement.executeUpdate();
} catch (SQLException ex) {
CustomControls.CustomTools.CustomMsgBox(ex.getMessage());
}
}
和第二张表
public void CreateTransactionsTable(){
try {
String SQL = "CREATE TABLE IF NOT EXISTS Transactions ("
+ "TransactionsNum INT(18) NOT NULL AUTO_INCREMENT,"
+ "TransactionsDate DATE,"
+ "TransactionsAmount float(8), "
+ "TransactionsUsername varchar(80) ,"
+ "PRIMARY KEY(TransactionsNum) , "
+ "FOREIGN KEY(TransactionsUsername) REFERENCES Users(Username) )"; // foregign key is the key in this table to accessed from main calling
//con = DBModule.ConnectDataBase.ConnectDataBase_Method();
statement = con.prepareStatement(SQL);
statement.executeUpdate();
} catch (SQLException ex) {
CustomControls.CustomTools.CustomMsgBox(ex.getMessage());
}
}
最后,这是更新数据库的语句
String addTRansSQL = "insert into transactions ( TransactionsDate , TransactionsAmount , TransactionsUsername ) "
+ " values( '" + sqlDate + "' , '" + tramount + "' , ' " + loggeduser + "' )";
答案 0 :(得分:0)
简而言之,您要尝试添加与用户表中不存在的用户的交易行,请尝试以下行“ SET FOREIGN_KEY_CHECKS = 0”