我试图在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
所以它没有默认值,但是我传给了命令一个正确的值,所以我不明白为什么会出现这个错误,不知道吗?
答案 0 :(得分:3)
最好的操作是将该列更改为其他文本,但如果您确实想要使用该列,则需要在该标识符周围添加反引号
command.CommandText = @"INSERT INTO competition (id, country_id, `name`, link)
VALUES (@id, @country_id, @name, @link)";