[英]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.