Click here to Skip to main content
15,889,335 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
hi dears,
I want read a table with "select * from ..." command in ASP.NET,
I wrote the code below:
C#
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);

what is my problem?
it's showed below error:
invalid coumn name
Posted
Updated 15-Dec-13 3:25am
v3
Comments
José Amílcar Casimiro 15-Dec-13 9:15am    
Probably the "fldpass" field is a string and is also missing the limiter string.
You must be careful with sql injection.
Mike Meinz 15-Dec-13 9:18am    
Please do not implement your web site using this code. A simple SQL Injection Attack will be able to destroy your database. Use SQLParameter Class to pass Textbox1.Text and Textbox2.Text to the SQL Select statement as parameters. This prevents SQL Injection attacks and provides better performance.

See Configuring Parameters and Parameter Data Types
[no name] 15-Dec-13 9:19am    
i want show sql injection to my classmate,
so need to run above code,
but it's showed invalid column name
Mike Meinz 15-Dec-13 9:21am    
You are missing the apostrophes surrounding Textbox2.Text value in the Select command.

string str = "select * from tbluser where flduser=" + "'" + TextBox1.Text.Trim() + "'" + " and fldpass=" + "'" + TextBox2.Text.Trim() + "'";
[no name] 15-Dec-13 9:23am    
thanks Mike Meinz
but where is my result(record of table)??

1 solution

You can't just go:
C#
SqlDataReader reader = command.ExecuteReader();
string selectedStudentName = Convert.ToString(reader);

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:
C#
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"];
   }
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900