字段名称没有默认值

时间:2018-05-26 14:10:07

标签: c# mysql

我试图在competition表格中插入具有此结构的记录:

CREATE TABLE IF NOT EXISTS `mydb`.`competition` (
  `id` INT NOT NULL,
  `country_id` INT NULL,
  `name` VARCHAR(255) NOT NULL,
  `link` VARCHAR(255) NOT NULL,
  PRIMARY KEY (`id`),
  INDEX `id_idx` (`country_id` ASC),
  CONSTRAINT `FK_country_competition_country_id`
    FOREIGN KEY (`country_id`)
    REFERENCES `mydb`.`country` (`id`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)
ENGINE = InnoDB;

我的代码有以下设计:

 using (MySqlConnection connection = new DBConnection().Connect())
 {
     using (MySqlCommand command = new MySqlCommand())
     {
         command.Connection = connection;           
         command.CommandText = "INSERT INTO competition (id, country_id, name, link) " +
                        "VALUES (@id, @country_id, @name, @link)";

         command.Parameters.AddWithValue("@id", 840);
         command.Parameters.AddWithValue("@country_id", 2);
         command.Parameters.AddWithValue("@name", "Superliga");
         command.Parameters.AddWithValue("@link", "https://int.soccerway.com/national/albania/super-league/20172018/regular-season/r42054/");
         command.ExecuteNonQuery();
       }
  }

当代码到达此行时:command.ExecuteNonQuery();

我明白了:

  

发生异常:CLR / MySQL.Data.MySqlClient.MySqlException   类型' MySQL.Data.MysqlClient.MySqlException'的例外情况发生在MySQL.Data.dll中但未在用户代码中处理:'字段' name'没有默认值'。

现在name表的字段competition被设置为NOT NULL所以它没有默认值,但是我传给了命令一个正确的值,所以我不明白为什么会出现这个错误,不知道吗?

1 个答案:

答案 0 :(得分:3)

名称是reserved keyword in MySql

最好的操作是将该列更改为其他文本,但如果您确实想要使用该列,则需要在该标识符周围添加反引号

command.CommandText = @"INSERT INTO competition (id, country_id, `name`, link)
                        VALUES (@id, @country_id, @name, @link)";