我不知道为什么会收到此错误:
C#代码:
using (MySqlConnection connection = new MySqlConnection("datasource=localhost;port=3306;database=project;username=***;password=***;"))
{
MySqlCommand cmd = new MySqlCommand("INSERT INTO student (studentID, studentFirstName, studentLastName, studentUserName, studentPassword) VALUES (@userID, @, @FirstName, @LastName, @Username, @Password);");
cmd.CommandType = CommandType.Text;
cmd.Connection = connection;
cmd.Parameters.AddWithValue("userID", Convert.ToInt32(textBoxUserID.Text));
cmd.Parameters.AddWithValue("@FirstName", textBoxFirstName.Text);
cmd.Parameters.AddWithValue("@LastName", textBoxLastName.Text);
cmd.Parameters.AddWithValue("@UserName", textBoxUsername.Text);
cmd.Parameters.AddWithValue("@Password", textBoxPassword.Text);
connection.Open();
cmd.Connection = connection;
cmd.ExecuteNonQuery();
MessageBox.Show("Saved");
connection.Close();
}
可能是因为我忽视了某些事情。
错误:
未处理的类型' MySql.Data.MySqlClient.MySqlException'发生在MySql.Data
中附加信息:列数与第1行的值计数不匹配
答案 0 :(得分:2)
格式化您的代码,您将清楚地看到所有语法问题:
string connectionString =
"datasource=localhost;port=3306;database=project;username=***;password=***;";
using (MySqlConnection connection = new MySqlConnection(connectionString)) {
connection.Open();
//DONE: keep sql readable
string sql =
@"INSERT INTO student (
studentID,
studentFirstName,
studentLastName,
studentUserName,
studentPassword)
VALUES (
@userID,
@FirstName, -- wrong @ param
@LastName,
@Username,
@Password);";
//DONE: wrap IDisposable into using
using (MySqlCommand cmd = new MySqlCommand(sql)) {
cmd.CommandType = CommandType.Text; // redundant
cmd.Connection = connection;
//DONE: separate code with new lines
// wrong parameter name
cmd.Parameters.AddWithValue("@userID", Convert.ToInt32(textBoxUserID.Text));
cmd.Parameters.AddWithValue("@FirstName", textBoxFirstName.Text);
cmd.Parameters.AddWithValue("@LastName", textBoxLastName.Text);
cmd.Parameters.AddWithValue("@UserName", textBoxUsername.Text);
cmd.Parameters.AddWithValue("@Password", textBoxPassword.Text);
cmd.ExecuteNonQuery();
}
}
MessageBox.Show("Saved");
答案 1 :(得分:0)
您在值子句中添加了一个附加参数(@ userID, @ ,
还要添加" @"在用户ID之前
cmd.Parameters.AddWithValue("userID", Convert.ToInt32(textBoxUserID.Text));
应该是
cmd.Parameters.AddWithValue("@userID", Convert.ToInt32(textBoxUserID.Text));