使用字符串变量查询字符串连接

时间:2014-02-22 17:00:32

标签: asp.net

我在此查询中遇到问题, 国家是一个变量。 错误:国家/地区列名无效..

cmd.CommandText = "SELECT [news_id], [news_title] from [upload_news] WHERE [city]="+ country;

1 个答案:

答案 0 :(得分:2)

尝试:

"SELECT [news_id], [news_title] from [upload_news] WHERE [city]='"+ country +"'";

但是如上所示,为select语句添加条件的正确方法是使用变量:

cmd.CommandText = "SELECT [news_id], [news_title] from [upload_news] WHERE [city]=@param"
cmd.Parameters.AddWithValue("param", country); 

PS:您的第一次尝试无法正常运行,因为您执行的实际SQL需要:

SELECT [news_id], [news_title] from [upload_news] WHERE [city] = USA

VS

SELECT [news_id], [news_title] from [upload_news] WHERE [city] = 'USA'