2011-01-25 29 views
1

這裏的SQL:C#的MySQL聲稱場過長

CREATE TABLE patients 
(
    patient_id INT AUTO_INCREMENT NOT NULL, 
    last_name VARCHAR(64) NOT NULL, 
    first_name VARCHAR(64), 
    sex  CHAR(1), 
    birth  DATE, 
    death  DATE, 
    PRIMARY KEY (patient_id) 
) ENGINE=INNODB; 

而這裏的C#:

  MySqlCommand insertCom = new MySqlCommand("INSERT INTO patients(" + 
       "last_name, first_name, sex, birth) VALUES" + 
       "('@lastName', '@firstName', '@sex', '@birthDate')", 
       connection); 

      /* ... */ 
      insertCom.Parameters.Add("@lastName", MySqlDbType.VarChar, 64); 
      insertCom.Parameters.Add("@firstName", MySqlDbType.VarChar, 64); 
      insertCom.Parameters.Add("@sex", MySqlDbType.Char, 1); 
      insertCom.Parameters.Add("@birthDate", MySqlDbType.Date); 

      insertCom.Parameters["@lastName"].Value = lastNameBox.Text; 
      insertCom.Parameters["@firstName"].Value = firstNameBox.Text; 
      insertCom.Parameters["@sex"].Value = (sexBox.Text == "Male" ? 'M' : 'F'); 
      insertCom.Parameters["@birthDate"].Value = birthDatePicker.Text; 

這是我直接在SQL中輸入數據:

INSERT INTO patients(last_name, first_name, sex, birth, death) 
VALUES 
    ('DeLarge', 'Alexandra', 'F', '1975-12-02', NULL) 

上面的工作和我寫的C#代碼基於此。但是C#代碼生成這個: MySql.Data.MySqlClient.MySqlException: Data too long for column 'sex' at row 1。 什麼給?

+0

我的第一個想法是,該表預計latin1或utf-8數據,並得到它在UTF-16。在utf-16中,CHAR(1)至少爲2個字節。在latin1中,CHAR(1)是1個字節。在utf-8中,CHAR(1)至少爲1個字節。但是,我沒有使用.NET的MySQL,所以我不能確定。 – Powerlord 2011-01-25 16:57:15

回答

3

您不應該在參數名稱周圍使用單引號。嘗試像這樣代替:

MySqlCommand insertCom = new MySqlCommand("INSERT INTO patients(" + 
      "last_name, first_name, sex, birth) VALUES" + 
      "(@lastName, @firstName, @sex, @birthDate)", 
      connection); 
0

啊哈,發現你的問題。我覺得你的MySQL應該是:

MySqlCommand("INSERT INTO patients(" + 
       "last_name, first_name, sex, birth) VALUES" + 
       "(@lastName, @firstName, @sex, @birthDate)" 

因爲你想插入的是('DeLarge', 'Alexandra', 'F', '1975-12-02', NULL) 但是,你的命令使然插入:('@lastName', '@firstName', '@sex', '@birthDate') 和MySQL正在迎頭趕上,該值'@sex'過大,可安裝在單個字符

從您的命令中取出',讓C#處理所有數據類型並格式化它自己。