我正在尝试使用下面的C#代码将一些数据插入MySQL数据库。如果我运行此命令,它将引发如下异常:
some error: You have an error in your SQL syntax; check the manual that correspo
nds to your MySQL server version for the right syntax to use near ': The Third Reich,
,
' at line 25
某处有语法错误吗?我找不到任何错误。
var rowContent = String.Format(@"
INSERT INTO animes
(
`JapanTitle`,
`AmericanTitle`,
`GermanTitle`,
`AnimeType`,
`CoverPath`,
`Episodes`,
`MinutesPerEpisodes`,
`JapanStatus`,
`AmericanStatus`,
`GermanStatus`,
`JapanTimeSpan`,
`AmericanTimeSpan`,
`GermanTimeSpan`,
`MainGenres`,
`SubGenres`,
`JapanStudios`,
`AmericanStudios`,
`GermanStudios`,
`GermanDescription`,
`EnglishDescription`)
VALUES
({0},
{1},
{2},
{3},
{4},
{5},
{6},
{7},
{8},
{9},
{10},
{11},
{12},
{13},
{14},
{15},
{16},
{17},
{18},
{19});", entity.JapanTitle,
entity.AmericanTitle,
entity.GermanTitle,
entity.AnimeType.ToString(),
entity.WallPaper.FileName,
entity.Episodes,
entity.MinutesPerEpisode,
entity.JapanStatus.ToString(),
entity.AmericanStatus.ToString(),
entity.GermanStatus.ToString(),
entity.JapanTimeSpan.ToString(),
entity.AmericanTimeSpan.ToString(),
entity.GermanTimeSpan.ToString(),
string.Join(",", entity.MainGenres),
string.Join(",", entity.SubGenres),
string.Join(",", entity.JapanStudios),
string.Join(",", entity.AmericanStudios),
string.Join(",", entity.GermanStudios),
entity.GermanDescription,
entity.EnglishDescription);
如果我看这段代码,我认为这是非常糟糕的代码。有没有更好的方法可以在没有诸如实体框架之类的数据库中插入许多列?
您的主要错误是由字符串周围缺少引号引起的。在sql命令文本中,当您要为文本字段传递值时,需要将此值放在单引号之间。
但是,如果在值周围加上适当的引号,则还有另一个大问题,称为Sql Injection。
使用这样的命令的唯一安全方法是通过参数化查询。
这样的事情(因为太长,我会削减您的代码)
string cmdText = @"INSERT INTO animes
(JapanTitle,AmericanTitle,GermanTitle,AnimeType,.....)
VALUES(@japtitle, @usatitle, @germantitle, @animtype, ....)";
MySqlCommand cmd = new MySqlCommand(cmdText, connection);
cmd.Parameters.AddWithValue("@japtitle", entity.JapanTitle);
cmd.Parameters.AddWithValue("@usatitle", entity.AmericanTitle);
cmd.Parameters.AddWithValue("@germantitle", entity.GermanTitle);
cmd.Parameters.AddWithValue("@animtype", entity.AnimeType);
....
cmd.ExecuteNonQuery();
这样,您不会直接在命令文本中写入值,而是在参数值中放置占位符。数据库引擎将确定如何使用命令中传递的参数。(无需担心字符串周围的引号或转义为值一部分的引号)
还要注意,Parameters集合的AddWithValue方法具有其自身的怪癖。您需要传递具有数据库字段期望的确切数据类型的值(因此,如果该字段需要整数,则对于AnimeType来说,没有ToString())
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句