Click here to Skip to main content
15,897,371 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
hii,


i have question that when i fetch data from database and if in the databse have some quoted dat e.g. D`DUN. this data is inserted in DB. when i execute select query like :

      Select city from glmast where glname='" + list_customer.Items[i].Value + "'

in list_cutomer  there is data in which some data are inserted like D`DUN like quotes. so it gives error like unclosed Quotation. 

so, how this will be solved because not all field contain Quotes.

Please Help Me..
Mitesh
Posted

1 solution

Do not concatenate strings to build a SQL command. It leaves you wide open to accidental or deliberate SQL Injection attack which can destroy your entire database. Use Parametrized queries instead.
VB
Using con As New SqlConnection(strConnect)
	con.Open()
	Using cmd As New SqlCommand("SELECT city FROM glmast WHERE glname=@GLN", con)
                cmd.Parameters.AddWithValue("@GLN", list_customer.Items[i].Value)
		Using reader As SqlDataReader = cmd.ExecuteReader()
			While reader.Read()
				Console.WriteLine("City: {0}", reader("city"))
			End While
		End Using
	End Using
End Using
Doing this will also cure your problem...


"can you caonvert this vb code to c# code ? please"


C#
using (SqlConnection con = new SqlConnection(strConnect))
   {
   con.Open();
   using (SqlCommand cmd = new SqlCommand("SELECT city FROM glmast WHERE glname=@GLN", con))
      {
      cmd.Parameters.AddWithValue("@GLN",list_customer.Items[i].Value);
      using (SqlDataReader reader = cmd.ExecuteReader())
         {
         while (reader.Read())
            {
            Console.WriteLine("City: {0}", reader["city"]));
            }
         }
      }
   }


[edit]Fixed C# conversion - OriginalGriff[/edit]
 
Share this answer
 
v3
Comments
AshishChaudha 30-Jun-12 5:23am    
my 5!
[no name] 30-Jun-12 5:54am    
when any record found i want to set that record into one variable like :
if (ds1.Tables[0].Rows.Count != 0)
{
get_code = get_code + ds1.Tables[0].Rows[0][0].ToString() + ",";
}
[no name] 30-Jun-12 7:07am    
dear , it gives error on using (SqlDataReader reader As SqlDataReader = cmd.ExecuteReader()) statement in that 'As' invalid Expression term.
OriginalGriff 30-Jun-12 7:24am    
Fixed - Oops!
That'll teach me to do a manual conversion instead of automatic! :O
Sorry about that...

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