我正在尝试从SQL Server的某个表中获取项目列表。我是用Visual Studio 2010做的。
这是我的代码:
static string filter = "25";
DataSet Datos = new DataSet();
SqlConnection MyConnection = default(SqlConnection);
SqlDataAdapter MyDataAdapter = default(SqlDataAdapter);
MyConnection = new SqlConnection("Initial Catalog=MyDataBase;Data Source=MyServer;Integrated Security=false;User ID=SQLUser;Password=SQLPass;");
MyDataAdapter = new SqlDataAdapter("SELECT Comment FROM MyTable WHERE [No_] = "+filter+" , MyConnection);
MyDataAdapter.SelectCommand.CommandType = CommandType.Text;
MyDataAdapter.Fill(Datos);
MyDataAdapter.Dispose();
MyConnection.Close();
我收到了这个错误:
参数1:无法从'string'转换为'System.Data.SqlClient.SqlCommand'
在这一行:
MyDataAdapter = new SqlDataAdapter("SELECT Comment FROM MyTable WHERE [No_] = "+filter+" , MyConnection);
那么,我怎样才能将字符串放入SqlConnection
?
提前致谢。
答案 0 :(得分:1)
这对我有用:
string filter = "10";
DataSet Datos = new DataSet();
string connectionString = "<your connection string here>";
string selectCommand =
"SELECT * FROM myTable WHERE Id = " + filter;
using (var MyConnection = new SqlConnection(connectionString))
using (var MyDataAdapter = new SqlDataAdapter(selectCommand, MyConnection))
{
MyDataAdapter.SelectCommand.CommandType = CommandType.Text;
MyDataAdapter.Fill(Datos);
}
这基本上是您的代码,使用using语法。如果您仍然遇到问题,请尝试并发布。祝你好运!