我有以下INSERT:
public static void insertStudent(int personId, string firstName, string lastName, string DOB, int phoneNumber, string address, int postCode, string majorField, int gradePointAverage)
{
MySqlConnection conn;
MySqlCommand cmd;
string sql = "INSERT INTO person (personId, firstName, lastName, DOB, phoneNumber, address, postCode) VALUES (@personId, @firstName, @lastName, @DOB, @phoneNumber, @address, @postCode)";
GetConnection(out conn, out cmd, sql);
try
{
cmd.Parameters.AddWithValue("@personId", personId);
cmd.Parameters.AddWithValue("@firstName", firstName);
cmd.Parameters.AddWithValue("@lastName", lastName);
cmd.Parameters.AddWithValue("@DOB", DOB);
cmd.Parameters.AddWithValue("@phoneNumber", phoneNumber);
cmd.Parameters.AddWithValue("@address", address);
cmd.Parameters.AddWithValue("@postCode", postCode);
cmd.ExecuteNonQuery();
long id = (long)cmd.LastInsertedId;
sql = "INSERT INTO student (Person_PersonId, majorField , gradePointAverage) VALUES (" + id + ",@majorField, @gradePointAverage";
cmd = new MySqlCommand(sql, conn);
cmd.Parameters.AddWithValue("@majorField", majorField);
cmd.Parameters.AddWithValue("@gradePointAverage", gradePointAverage);
cmd.ExecuteNonQuery();
}
catch (NullReferenceException nre)
{
MessageBox.Show(nre.Message);
}
catch (Exception e)
{
MessageBox.Show(e.Message);
}
finally
{
try
{
MessageBox.Show("New student record created created.");
cmd.Connection.Close();
conn.Close();
}
catch (Exception e)
{
MessageBox.Show(e.Message);
}
}
}
由此按钮执行:
private void btnInsertStudentNumberAdmin_Click(object sender, EventArgs e)
{
StudentHelperClass.insertStudent(int.Parse(txtPersonIDStudent.Text), txtFirstNameStudent.Text, txtLastNameStudent.Text, txtDOBStudent.Text, int.Parse(txtPhoneNumberStudent.Text), txtAddressStudent.Text, int.Parse(txtPostCodeStudent.Text), txtMajorFieldStudent.Text, int.Parse(txtGpaStudent.Text));
}
但是点击后,我会看到一个消息框,显示you have an error in your SQL syntax; check the manual that corresponds to your mySql server version for the right version for the right syntax to use near " at line 1
,然后插入person
表的条目,但学生的条目不会插入。
我确保所有int
都是int,所有strings
都是字符串。我不确定是什么问题。
答案 0 :(得分:3)
sql = "INSERT INTO student (
Person_PersonId,
majorField,
gradePointAverage
) VALUES (" + id + ",
@majorField,
@gradePointAverage";
缺少一个近括号。它应该是:
sql = "INSERT INTO student (
Person_PersonId,
majorField,
gradePointAverage
) VALUES (" + id + ",
@majorField,
@gradePointAverage
)";
答案 1 :(得分:3)
sql =“INSERT INTO student(Person_PersonId,majorField,gradePointAverage)VALUES(”+ id +“,@ majorField,@gradePointAverage)”; 错过了结局)......?