Click here to Skip to main content
15,917,622 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
is there any solution beside this code that we can implement to add value in database ? that are more secure than this code below.

What I have tried:

OleDbCommand cmd = con.CreateCommand();    
    con.Open();    
    cmd.CommandText = "Insert into Student(FirstName,LastName)Values('" + textBox1.Text + "','" + textBox2.Text + "')";    
    cmd.Connection = con;    
    cmd.ExecuteNonQuery();    
    MessageBox.Show("Record Submitted","Congrats");    
    con.Close();   
Posted
Updated 30-Jul-17 20:09pm

Yes: instead of string concatenation, use parameterized queries:
C#
OleDbCommand cmd = new OleDbCommand("Insert into Student(FirstName,LastName)Values(@FirstName,@LastName)", con);
cmd.Parameters.AddWithValue("@FirstName", textBox1.Text);
cmd.Parameters.AddWithValue("@LastName", textBox2.Text);

The advantages of this:

  • It's easier to read: there are less quotes to be confused about, so it's harder to have a syntax error here.
  • Your original code has an SQL injection[^] vulnerability, which is closed by using parameterized queries.
 
Share this answer
 
Do not do it like that! Never 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.

You should also use a try ... catch block around your DB code, and either a finally block to close and dispose the Command and Connection objects, or using blocks to do that automatically.
 
Share this answer
 
First of all NEVER use string concatenation to create you query. Certain user input can harm you very badly... xkcd: Exploits of a Mom[^]
It is not clear from your code, but if you do not, than add username and password to your connection...
 
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