Solved

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

Posted on 2008-10-24
3
245 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

Courses: Start Training Online With Pros, Today

Brush up on the basics or master the advanced techniques required to earn essential industry certifications, with Courses. Enroll in a course and start learning today. Training topics range from Android App Dev to the Xen Virtualization Platform.

Question has a verified solution.

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

Flash (http://en.wikipedia.org/wiki/Adobe_Flash) has evolved over the years to where it has become a masterful tool for displaying content screen.  It has excellent layout placement, UI precision as well as rendering capabilities. This, along with t…
For those of you who don't follow the news, or just happen to live under rocks, Microsoft Research released a beta SDK (http://www.microsoft.com/en-us/download/details.aspx?id=27876) for the Xbox 360 Kinect. If you don't know what a Kinect is (http:…
This tutorial gives a high-level tour of the interface of Marketo (a marketing automation tool to help businesses track and engage prospective customers and drive them to purchase). You will see the main areas including Marketing Activities, Design …
The Email Laundry PDF encryption service allows companies to send confidential encrypted  emails to anybody. The PDF document can also contain attachments that are embedded in the encrypted PDF. The password is randomly generated by The Email Laundr…

776 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