ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

字段名称没有默认值

2019-11-09 02:15:05  阅读:13  来源: 互联网

标签:c mysql



我正在尝试在竞赛表中插入具有以下结构的记录:

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();

我得到:

Exception has occurred: CLR/MySQL.Data.MySqlClient.MySqlException
An exception of type ‘MySQL.Data.MysqlClient.MySqlException’ occurred in MySQL.Data.dll but was not handled in user code: ‘field ‘name’ doesn’t have a default value’.

现在,竞赛表的字段名称设置为NOT NULL,因此它没有默认值,但是我将正确的值传递给命令,所以我不明白为什么会显示此错误,有什么想法吗?

解决方法:

名称是reserved keyword in MySql

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

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


标签:c,mysql

专注分享技术,共同学习,共同进步。侵权联系[admin#icode9.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有