Solved

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

Posted on 2008-10-24
3
247 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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

Welcome my friends to the second instalment and follow-up to our Minify and Concatenate Your Scripts and Stylesheets (http://www.experts-exchange.com/Programming/Languages/.NET/ASP.NET/A_4334-Minify-and-Concatenate-Your-Scripts-and-Stylesheets.html)…
This document covers how to connect to SQL Server and browse its contents.  It is meant for those new to Visual Studio and/or working with Microsoft SQL Server.  It is not a guide to building SQL Server database connections in your code.  This is mo…
Attackers love to prey on accounts that have privileges. Reducing privileged accounts and protecting privileged accounts therefore is paramount. Users, groups, and service accounts need to be protected to help protect the entire Active Directory …

733 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