Solved

How do I include multiple parameters in a SQL query in C#.net?

Posted on 2008-10-24
3
246 Views
Last Modified: 2013-12-17
I have a form that I accept inputs from 5 text boxes.
I want to be able to include each input from the text boxes in my insert into query.
I want to use parameters to prevent database injection.
I also want to update the field in the database as NULL if nothing was entered in a text box.
I am using a SQL backend.

Could you please show me a working coded example of how to this?

0
Comment
Question by:wademi
  • 2
3 Comments
 
LVL 32

Expert Comment

by:Daniel Wilson
ID: 22799487

String SQL = "Insert into MyTable(Field1, Field2, Field3, Field4, Field5) Values (@Val1, @val2, @Val3, @Val4, @Val5)";
SqlCommand cmd = new SqlCommand(new SqlConnection(MyConnStr), SQL);
SqlParameter P;
 
P = new SqlParameter("@Val1",SqlDbType.VarChar);
P.Value = Text1.Text
cmd.Parameters.Add(P);
 
P = new SqlParameter("@Val2",SqlDbType.VarChar);
P.Value = Text2.Text
cmd.Parameters.Add(P);
 
//etc.
 
cmd.ExecuteNonQuery();

Open in new window

0
 
LVL 32

Accepted Solution

by:
Daniel Wilson earned 500 total points
ID: 22799523
Oh, I didn't get the NULL ...

for line 6:

if (Text1.Text.Trim.Length > 0){
  P.Value = Text1.Text;
}else{
  P.Value = System.Data.DBNull.Value;
}
0
 

Author Closing Comment

by:wademi
ID: 31509788
Thanks
0

Featured Post

Announcing the Most Valuable Experts of 2016

MVEs are more concerned with the satisfaction of those they help than with the considerable points they can earn. They are the types of people you feel privileged to call colleagues. Join us in honoring this amazing group of Experts.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Summary Displaying images in RichTextBox is a common requirement with limited solutions available. Pasting through clipboard or embedding into RTF content only support static images.  This article describes how to insert Windows control objects int…
In my previous article (http://www.experts-exchange.com/Programming/Languages/.NET/.NET_Framework_3.x/A_4362-Serialization-in-NET-1.html) we saw the basics of serialization and how types/objects can be serialized to Binary format. In this blog we wi…
This video shows how to use Hyena, from SystemTools Software, to bulk import 100 user accounts from an external text file. View in 1080p for best video quality.
Nobody understands Phishing better than an anti-spam company. That’s why we are providing Phishing Awareness Training to our customers. According to a report by Verizon, only 3% of targeted users report malicious emails to management. With compan…

840 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question