Solved

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

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

Threat Intelligence Starter Resources

Integrating threat intelligence can be challenging, and not all companies are ready. These resources can help you build awareness and prepare for defense.

Join & Write a Comment

Normally the drop down box control found in the .Net framework tools is able to select just one data and value at a time, which is displayed on the text area.   But what if you want to have multiple values to be selected in the drop down box? As …
It seems a simple enough task, yet I see repeated questions asking how to do it: how to pass data between two forms. In this article, I will show you the different mechanisms available for you to do just that. This article is directed towards the .N…
Here's a very brief overview of the methods PRTG Network Monitor (https://www.paessler.com/prtg) offers for monitoring bandwidth, to help you decide which methods you´d like to investigate in more detail.  The methods are covered in more detail in o…
When you create an app prototype with Adobe XD, you can insert system screens -- sharing or Control Center, for example -- with just a few clicks. This video shows you how. You can take the full course on Experts Exchange at http://bit.ly/XDcourse.

705 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

Need Help in Real-Time?

Connect with top rated Experts

15 Experts available now in Live!

Get 1:1 Help Now