这是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
。
是什么给了什么?
答案 0 :(得分:3)
参数名称周围不应有单引号。请尝试这样:
MySqlCommand insertCom = new MySqlCommand("INSERT INTO patients(" +
"last_name, first_name, sex, birth) VALUES" +
"(@lastName, @firstName, @sex, @birthDate)",
connection);
答案 1 :(得分:0)
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#处理所有数据类型和格式化本身。