473,803 Members | 4,458 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Elegant, clean and safe way of having multiple concurent parameters in a dbCommand

consider the following oversimplified and fictional code
public void CreateInvoices( Invoice[] invoices)
{
IDbCommand command=Util.Cr eateDbCommand() ;
foreach(Invoice invoice in invoices) //lets say you have 200
invoices
{
command.Command Text+="INSERT INTO Invoice(Amount)
VALUES(@Amount) ; ";
Util.AddParamTo DbCommand("@Amo unt", invoice.Amount, command);
}

if(command.Comm andText!=String .Empty)
{
try
{
command.Execute NonQuery();
}
catch(Exception ex)
{
//something here
}
}
}

/*************** *************** *************** *************** **************
Problem: We can't add multiple parameters with the same name
Possible Solution: Change foreach loop with a for loop and assign a
number at the end of each parameter (which is not clean)
*************** *************** *************** *************** **************/
public void CreateInvoices2 (Invoice[] invoices)
{
IDbCommand command=Util.Cr eateDbCommand() ;
foreach(Invoice invoice in invoices) //lets say you have 200
invoices
{
command.Command Text+=String.Fo rmat("INSERT INTO
Invoice(Amount) VALUES({0}); ", invoice.Amount) ;
}

if(command.Comm andText!=null)
{
try
{
command.Execute NonQuery();
}
catch(Exception ex)
{
//something here
}
}
}

/*************** *************** *************** *************** *************** *
Problem: It seem that the ToString() function take into account the
culture info of the current thread
so in some cultures you have a different decimal number separator than
the one needed in the database
Possible solution: Set the culture info of the current thread to us-En
or do invoice.Amount. ToString(new CultureInfo("en-US")) which is not
clean either
*************** *************** *************** *************** *************** */
I was wondering if there was any cleaner and more 'natural' way to do
this than using one of the solutions described above.

Jul 19 '06 #1
4 1517
Hello ar*****@email.c om,

First, the INSERT sql statement will only allow you to insert ONE (count
them.. ONE) record at a time.
So each time through the loop you MUST call .ExecuteNonQuer y().

Second, if a parameter with the name you want to use already exists on the
command object then you should either clear all parameters and start over..
or just assign a new value to the existing parameter.

Third, numeric values are culture-independant. DO NOT turn them into strings.

-Boo

consider the following oversimplified and fictional code

public void CreateInvoices( Invoice[] invoices)
{
IDbCommand command=Util.Cr eateDbCommand() ;
foreach(Invoice invoice in invoices) //lets say you have 200
invoices
{
command.Command Text+="INSERT INTO Invoice(Amount)
VALUES(@Amount) ; ";
Util.AddParamTo DbCommand("@Amo unt", invoice.Amount, command);
}
if(command.Comm andText!=String .Empty)
{
try
{
command.Execute NonQuery();
}
catch(Exception ex)
{
//something here
}
}
}
/*************** *************** *************** *************** *********
*****
Problem: We can't add multiple parameters with the same name
Possible Solution: Change foreach loop with a for loop and assign a
number at the end of each parameter (which is not clean)
*************** *************** *************** *************** **********
****/
public void CreateInvoices2 (Invoice[] invoices)
{
IDbCommand command=Util.Cr eateDbCommand() ;
foreach(Invoice invoice in invoices) //lets say you have 200
invoices
{
command.Command Text+=String.Fo rmat("INSERT INTO
Invoice(Amount) VALUES({0}); ", invoice.Amount) ;
}
if(command.Comm andText!=null)
{
try
{
command.Execute NonQuery();
}
catch(Exception ex)
{
//something here
}
}
}
/*************** *************** *************** *************** *********
*******
Problem: It seem that the ToString() function take into account the
culture info of the current thread
so in some cultures you have a different decimal number separator than
the one needed in the database
Possible solution: Set the culture info of the current thread to us-En
or do invoice.Amount. ToString(new CultureInfo("en-US")) which is not
clean either
*************** *************** *************** *************** **********
******/
I was wondering if there was any cleaner and more 'natural' way to do
this than using one of the solutions described above.

Jul 20 '06 #2
I would recommend using a SqlDataAdapter for this and create a data set
which has the values you want to insert into the table. You can tell the
SqlDataAdapter (in .NET 2.0) to batch the commands, and it will take care of
putting everything together for you (the commands, the parameters, etc,
etc).

Hope this helps.
--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard. caspershouse.co m

<ar*****@email. comwrote in message
news:11******** **************@ s13g2000cwa.goo glegroups.com.. .
consider the following oversimplified and fictional code
public void CreateInvoices( Invoice[] invoices)
{
IDbCommand command=Util.Cr eateDbCommand() ;
foreach(Invoice invoice in invoices) //lets say you have 200
invoices
{
command.Command Text+="INSERT INTO Invoice(Amount)
VALUES(@Amount) ; ";
Util.AddParamTo DbCommand("@Amo unt", invoice.Amount, command);
}

if(command.Comm andText!=String .Empty)
{
try
{
command.Execute NonQuery();
}
catch(Exception ex)
{
//something here
}
}
}

/*************** *************** *************** *************** **************
Problem: We can't add multiple parameters with the same name
Possible Solution: Change foreach loop with a for loop and assign a
number at the end of each parameter (which is not clean)
*************** *************** *************** *************** **************/
public void CreateInvoices2 (Invoice[] invoices)
{
IDbCommand command=Util.Cr eateDbCommand() ;
foreach(Invoice invoice in invoices) //lets say you have 200
invoices
{
command.Command Text+=String.Fo rmat("INSERT INTO
Invoice(Amount) VALUES({0}); ", invoice.Amount) ;
}

if(command.Comm andText!=null)
{
try
{
command.Execute NonQuery();
}
catch(Exception ex)
{
//something here
}
}
}

/*************** *************** *************** *************** *************** *
Problem: It seem that the ToString() function take into account the
culture info of the current thread
so in some cultures you have a different decimal number separator than
the one needed in the database
Possible solution: Set the culture info of the current thread to us-En
or do invoice.Amount. ToString(new CultureInfo("en-US")) which is not
clean either
*************** *************** *************** *************** *************** */
I was wondering if there was any cleaner and more 'natural' way to do
this than using one of the solutions described above.

Jul 20 '06 #3
<ar*****@email. comwrote in message
news:11******** **************@ s13g2000cwa.goo glegroups.com.. .
consider the following oversimplified and fictional code
considered...
>
/*************** *************** *************** *************** **************
Problem: We can't add multiple parameters with the same name
Possible Solution: Change foreach loop with a for loop and assign a
number at the end of each parameter (which is not clean)
*************** *************** *************** *************** **************/
considered more...
/*************** *************** *************** *************** *************** *
Problem: It seem that the ToString() function take into account the
culture info of the current thread
so in some cultures you have a different decimal number separator than
the one needed in the database
Possible solution: Set the culture info of the current thread to us-En
or do invoice.Amount. ToString(new CultureInfo("en-US")) which is not
clean either
*************** *************** *************** *************** *************** */
I was wondering if there was any cleaner and more 'natural' way to do
this than using one of the solutions described above.
Rather than using new CultureInfo(), use
invoice.Amount. ToString(Cultur eInfo.Invariant Culture) to always get the
culture-invariant number representation. Of course, converting parameters
to literal strings opens the potential for SQL injection attacks so you
should use caution. Numeric types don't pose any risk, but if you have any
text columns, you need to SQL-quote them before pasting them into your
generated SQL text.

On the SQL itself, you have a couple of options. First, you could generate
new parameter names each time through the loop, but you'll be subject to the
whim of the provider with regard to limits on the number of named parameters
allowed. SQL Server allows up to 2100 named parameters, but other DB
providers will vary. If you never have more than "a few" (whatever that
means) items, you'd probably be safe generating a new parameter name for
each iteration of the loop. I guess you don't consider this option to be
"clean" - it does have it's limitations, but it shouldn't be dismissed
outright IMO.

Regardless of whether you come up with a way to parameterize the SQL, you
can also improve the efficiency of your inserts by inserting more than one
row per statement. A couple of structures that can be used are:

insert into Table (c1, c2, c3)
select 1 as c1, 2 as c2, 3 as c3
union all select 4,5,6
union all select 7,8,9
You can cascade as many "union all select" clauses as you want, but the
"sweet spot" will be fairly small - probably 10 or fewer, otherwise query
compilation time gets to be too high.

Another possiblity is:

insert into Table(c1, c2, c3)
exec(@'
select 1, 2, 3
select 4, 5, 6
select 7, 8, 9
')

Again, you can add as many selects as you want, but the sweet spot will be
fairly small - but larger than the construct above. In one application,
using this construct improved insert speed by nearly a factor of 4 over
simple scalar inserts.

Of course, depending on how many database backends you need to target,
neither of these may work. Both will work with SQL server 2000 or 2005.

HTH

-cd
Jul 20 '06 #4
"Nicholas Paldino [.NET/C# MVP]" <mv*@spam.guard .caspershouse.c omwrote in
message news:%2******** *******@TK2MSFT NGP05.phx.gbl.. .
I would recommend using a SqlDataAdapter for this and create a data set
which has the values you want to insert into the table. You can tell the
SqlDataAdapter (in .NET 2.0) to batch the commands, and it will take care
of putting everything together for you (the commands, the parameters, etc,
etc).
Out of curiousity - do you know what kind of SQL it generates for batched
inserts?

-cd
Jul 20 '06 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

6
5025
by: Kamilche | last post by:
Is there a more elegant way to change the working directory of Python to the directory of the currently executing script, and add a folder called 'Shared' to the Python search path? This is what I have. It seems like it could be shorter, somehow. # Switch Python to the current directory import os, sys pathname, scriptname = os.path.split(sys.argv) pathname = os.path.abspath(pathname)
9
2113
by: Paul Morrow | last post by:
I have seen the technique where a number of rows in a database are displayed in an html table so that each column of each row is editable. They use a single form surrounding the table, where each field in any given column has the same control name. So for example, in the last_name column, every row in the table would contain an input field (of type "text") with the name "last_name". Is this safe to do? I know that multiple radio...
3
7982
by: Grandma Wilkerson | last post by:
Hi, The documentation states that enumeration through a collection is inherently NOT thread-safe, since a thread which added/removed an item from said collection could screw up the thread that was iterating. That makes sense.. but... given a collection that is filled at start-time and never modified again, is it safe to have multiple threads *reading* (not writing to) the collection using foreach()? I have a class that exposes an...
7
2247
by: Felix Kater | last post by:
Hi, when I need to execute a general clean-up procedure (inside of a function) just before the function returns -- how do I do that when there are several returns spread over the whole function? My first approach: Use "while(1)" and "break", however this doesn't work if there is another loop inside (since I can't break two loops at the same time):
1
5156
by: Dotnet Gruven | last post by:
I've posted this in the adonet group, however it was suggested I might have better luck here.... ============================================================= I'm trying to use a typed dataset and ObjectDataSource binding to a SQLX db using a foreign key to filter the returned result set to display in a GridView. The error message in the subject line is generated when I try to bind the following GridView to the ObjectSource that follows...
1
8152
by: Garth Wells | last post by:
Using an example in the Jan 2006 release of the Enterprise Library, I came up with the code shown below to create a DAL method for returning several columns of a single row. I place the output parameter values in a comma-separated string, and then split the string to get the individual values on the calling page. This approach works, but I can't help but think there is a more efficient way to accomplish this. Thanks for any insight you...
32
2050
by: r.z. | last post by:
class vector3 { public: union { float data; struct { float x, y, z; };
3
3307
by: JM | last post by:
Hi, I am using SQL Server 2000 and ASP.NET 2.0 and want to call a stored procedure using Latest Enterprise Library 2.0. My stored procedure has 3 input parameters: CustId (int), RefId(int) and EmailId(varchar 200) and it returns a dataset. This is how I am trying to do: ------------- int CustId = 1
0
3867
by: nostradumbass77 | last post by:
Using Enterprise Library 2.0 (Jan 06) and .NET 2.0 (VB.Net 2005) Dim dbPF As Data.Common.DbProviderFactory Try dbPF = Data.Common.DbProviderFactories.GetFactory("System.Data.OleDb") db = New Microsoft.Practices.EnterpriseLibrary.Data.GenericDatabase( _ "Provider=Microsoft.Jet.OLEDB.4.0;Data
0
9564
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10316
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
9125
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7604
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5500
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5629
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4275
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3798
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2970
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.