撇号会导致查询问题

Har*_*nch 1 c# t-sql sql-server parameters wpf

当我对表的填充执行查询时,我只在两次出现时出错.特别是,当name字段有这样的值时:

K'Ogladbach
Run Code Online (Sandbox Code Playgroud)

现在撇号引起了一个问题,因为查询将此命令解释为新值,这是错误的.这是我在SQL中查询的结构:

string sql = @"insert into Team (name, code, shortName, squadMarketValue, 
                    crestUrl, link_self, link_fixtures, link_players, caption) 
                    values ('" + item.name + "', '" + item.code + "', '" +
                    item.shortName + "', '" + item.squadMarketValue + "', '" +
                    item.crestUrl + "', '" + item._links.self.href + "', '" +
                    item._links.fixtures.href + "', '" + item._links.players.href + "', '" + 
                    campionato + "')";
Run Code Online (Sandbox Code Playgroud)

你如何才能看到每个新值都被提出来' value ',所以如果在值中有" ' "一个问题,因为查询失败了表填充.希望有一个解决方案.

Dar*_*ren 7

使用SqlParamerterized查询而不是原始SQL.这将有助于防止SQL注入,并提供强大的解决方案.

SqlCommand command = new SqlCommand("INSERT INTO Team (name) VALUES (@name)", con);

command.Parameters.Add("@name", SqlDbType.NVarChar).Value = item.name;
// Add the rest of the parameters here

command.ExecuteNonQuery();  // Execute the command
Run Code Online (Sandbox Code Playgroud)