[英]C# MySQL claims a field is too long
Here's the SQL: 这是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;
And here's the C#: 这是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;
This is how I enter data directly in SQL: 这就是我直接在SQL中输入数据的方式:
INSERT INTO patients(last_name, first_name, sex, birth, death)
VALUES
('DeLarge', 'Alexandra', 'F', '1975-12-02', NULL)
The above works and I wrote the C# code based on that. 上面的作品,我基于此编写了C#代码。 But the C# code produces this:
MySql.Data.MySqlClient.MySqlException: Data too long for column 'sex' at row 1
. 但是C#代码会生成以下代码:
MySql.Data.MySqlClient.MySqlException: Data too long for column 'sex' at row 1
。 What gives? 是什么赋予了?
You should not have single quotes around the parameter names. 参数名称不应包含单引号。 Try it like this instead:
像这样尝试:
MySqlCommand insertCom = new MySqlCommand("INSERT INTO patients(" +
"last_name, first_name, sex, birth) VALUES" +
"(@lastName, @firstName, @sex, @birthDate)",
connection);
Ahah, found your problem. 啊,发现您的问题了。 I think your MySQL should be :
我认为您的MySQL应该是:
MySqlCommand("INSERT INTO patients(" +
"last_name, first_name, sex, birth) VALUES" +
"(@lastName, @firstName, @sex, @birthDate)"
Because what you're trying to insert is ('DeLarge', 'Alexandra', 'F', '1975-12-02', NULL)
But, your command dictates to insert : ('@lastName', '@firstName', '@sex', '@birthDate')
And MySQL is catching that the value '@sex'
is too big to fit in a single character 因为您要插入的是
('DeLarge', 'Alexandra', 'F', '1975-12-02', NULL)
但是,您的命令要求插入: ('@lastName', '@firstName', '@sex', '@birthDate')
并且MySQL注意到'@sex'
的值太大而无法容纳单个字符
Take out the '
from your command and let C# handle all the datatypes and formatting itself. 从命令中取出
'
,让C#处理所有数据类型并自行格式化。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.