Here's the 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#:
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:
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. But the C# code produces this: 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 :
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
Take out the '
from your command and let C# handle all the datatypes and formatting itself.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.