2017-02-27 29 views
-4

匹配值計數我不知道爲什麼我收到此錯誤:列數確實在第1行C#

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(); 
} 

這可能是由於我忽視的東西。

錯誤:

An unhandled exception of type 'MySql.Data.MySqlClient.MySqlException' occurred in MySql.Data

Additional information: Column count doesn't match value count at row 1

+0

其漂亮的自我解釋..你要我勺子你的一切飼料.. – CSEngine

+1

錯誤消息是返回是相當自我解釋。不,我不希望你做任何事情。 http://stackoverflow.com/questions/16704328/c-sharp-mysql-error-column-count-doesnt-match-value-count-at-row-1 – spencer7593

回答

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"); 
0

你在你的價值觀條款(@userID,@增加一個額外的參數,

也是用戶ID前添加 「@」

cmd.Parameters.AddWithValue("userID", Convert.ToInt32(textBoxUserID.Text)); 

應該是

cmd.Parameters.AddWithValue("@userID", Convert.ToInt32(textBoxUserID.Text)); 
+0

謝謝。這有很大幫助 – CSEngine

相關問題