SQL Select命令中的列名无效
问题描述:
嗨亲爱的,
我想在ASP.NET中读取一个带select * from ...命令的表,
我写了下面的代码:
hi dears,
I want read a table with "select * from ..." command in ASP.NET,
I wrote the code below:
SqlConnection con = new SqlConnection(@"Data Source=.\sql2008;Initial Catalog=test;Integrated Security=true;");
string str = "select * from tbluser where flduser='"+TextBox1.Text.Trim() +"' and fldpass=" + TextBox2.Text.Trim();
SqlCommand command = new SqlCommand(str, con);
con.Open();
SqlDataReader reader = command.ExecuteReader();
string selectedStudentName = Convert.ToString(reader);
我的问题是什么?
它显示如下错误:
无效的coumn名称
what is my problem?
it's showed below error:
invalid coumn name
答
你不能只是去:
You can't just go:
SqlDataReader reader = command.ExecuteReader();
string selectedStudentName = Convert.ToString(reader);
您需要实际读取db中的值,并使用参数化查询指定您想要的列(如Mike Meinz所说)。
试试这个:
You need to actually read the values from the db, and specify which column you want as weel as (as Mike Meinz says) using a parametrized query.
Try this:
string str = "select * from tbluser where flduser=@USER";
SqlCommand command = new SqlCommand(str, con);
con.Open();
command.Parameters.AddWithValue("@USER", TextBox1.Text.Trim());
SqlDataReader reader = command.ExecuteReader();
string selectedStudentName = "";
if (reader.Read())
{
selectedStudentName = (string) reader["NameOoColumnWithUserNameInIt"];
}