【问题标题】:C# MySQL claims a field is too longC# MySQL 声称一个字段太长
【发布时间】:2011-01-25 16:52:40
【问题描述】:

这是 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。 什么给了?

【问题讨论】:

  • 我的第一个想法是该表需要 latin1 或 utf-8 数据并且正在 utf-16 中获取它。在 utf-16 中,CHAR(1) 至少为 2 个字节。在 latin1 中,一个 CHAR(1) 是 1 个字节。在 utf-8 中,CHAR(1) 至少为 1 个字节。但是,我没有使用 .NET 中的 MySQL,所以我不能确定。

标签: c# sql mysql


【解决方案1】:

参数名称不应该有单引号。试试这样吧:

MySqlCommand insertCom = new MySqlCommand("INSERT INTO patients(" +
            "last_name, first_name, sex, birth) VALUES" + 
            "(@lastName, @firstName, @sex, @birthDate)",
            connection);

【讨论】:

    【解决方案2】:

    啊哈,发现你的问题了。我认为你的 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# 自行处理所有数据类型和格式设置。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-14
      • 2013-12-21
      • 2019-02-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多