2015-07-04 62 views
1

当我执行一个查询表的人口时,我只有两次出现错误。特别是,当名称字段有一些像这样的值:撇号导致查询问题

K'Ogladbach 

现在撇号会导致一个问题,因为查询解释像一个新值,这个命令,这是错误的。 这是我在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 + "')"; 

如何可以看到每一个新值由' value ' rapresented, 因此,如果在价值有一个" ' "这是一个问题,因为查询失败表人口。希望有一个解决方案。

+4

使用参数化查询的另一个理由 – Steve

+1

@HaroldFinch我想知道你真的想要做什么?你是否将SQL数据导出为CSV? – POQDavid

+1

了解有关[Bobby Tables](http://bobby-tables.com/)SQL注入的更多信息。 – HABO

回答

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 
+0

感谢您的帮助。 –

0

SqlParamerterized疑问是最好的办法

您还可以将取代'与'数据
这不是一个双引号 - 这是两个单引号
E.G. K'Ogladbach到K'Ogladbach