Click here to Skip to main content
15,893,663 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello there,

I was trying to run a simple INSERT query in which i passed a string value with hyphen ( ' ). It throws error. How can i insert/Update a string value with hyphen.
Front-End : VB.net, C#
Back-End : MS-Access, Sql Server

Table :

SID SName
1 ABC
2 DEF

Problem : Trying to insert Name = xyz's

Code :

VB
Dim Da As OleDbDataAdapter = New OleDbDataAdapter("Insert Into Student(SName) Values('" & txtUserName.Text & "')", Conn)
        Dim Ds As New DataSet
        Da.Fill(Ds)
Posted
Updated 13-Jun-14 19:54pm
v3
Comments
Awadhendra Tripathi 14-Jun-14 1:55am    
What is Datatype for that column?

1 solution

Use a parameterized query:
C#
string test = "O' what happened?";

using (SqlConnection cnx = new SqlConnection(connectionString)) {
   cnx.Open();
   using (SqlCommand cmd = new SqlCommand("INSERT INTO [TestTable] ([TestField]) VALUES (@value)", cnx)) {
      cmd.Parameters.AddWithValue("@value", test);
      int result = cmd.ExecuteNonQuery();
   }
}


Moreover, it will have the advantage of bulletproofing your code to SQL injection attacks.
Parameterized queries should be used everywhere user input is involved.
Good luck :)
 
Share this answer
 
Comments
Raghubir_Sarkar 14-Jun-14 2:02am    
Thanks phil it works, and also for your suggestion next time i'll use SqlCommand instead of dataadapter.
phil.o 14-Jun-14 4:02am    
Why next time? As far as security is concerned, you should use parameterized queries whenever an unkown input source (user, file, db...) is involved. :)
For example, if someone enters ';DROP TABLE Student-- in txtUserName, with your initial code you just lost the Student table; with a parameterized query the string would be inserted in the SName column, without any harm done to the database schema.
Raghubir_Sarkar 14-Jun-14 5:56am    
You are right phil but My current project is too lengthy so it is not possible to change all insert or update queries. In future projects and new forms in current project i'll use parameterized quiry. Thank you so much for your support.

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