[英]C# MySQL claims a field is too long
這是SQL:
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
。 是什么賦予了?
參數名稱不應包含單引號。 像這樣嘗試:
MySqlCommand insertCom = new MySqlCommand("INSERT INTO patients(" +
"last_name, first_name, sex, birth) VALUES" +
"(@lastName, @firstName, @sex, @birthDate)",
connection);
啊,發現您的問題了。 我認為您的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#處理所有數據類型並自行格式化。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.