Click here to Skip to main content
15,890,282 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,

I'm having 2 string array and 1 integer array of size 100. I need to insert them (100 rows) into table.

query= insert into storage (box_no,item_name,amount) values x,y,z

for(i=0;i<100;i++)

x=arr1[i]
y=arr2[i]
z=arr3[i]



How can I optimize the query, may be using command.parameter.addwithvalue

Thanks

Note: Not sure if the question is regarding MySQL (Tags are there), because original question was for msql (maybe a typo for mssql).
Posted
Updated 14-Sep-11 11:57am
v4

1 solution

I am assuming that you are using MySQL, because in your original question you didnt mentioned MySQL. But I see tags added as MySQL and VB.NET

if there are only 100 rows you want to insert in a loop, you will not see much of a difference when you optimize. but if you want to insert lot of rows (more than 10,000) in bulk, the best way is to create a data adapter then fill a dataset, set the primary key on dataset same as actual table, then add rows into the dataset (in memory), and then fire datadapter.update() and pass the dataset. this way the data adapter will insert the records most effeciently (same when you want to update in bulk).

but in your case you should not worry too much about the performance as it's only 100 rows (you will not see that milisecond improvement). but you should avoid any sql injection attacks by passing the values with parameter. for security never use inline sql.

(like
SQL
string strQuery = "Select * From Users Where Password = '" + strPassword + "' And UserName = '" + strUserName + "'
").

always use parameter, (or call stored procedure)

VB
Dim da As MySqlDataAdapter = New MySqlDataAdapter()
Dim cmd As MySqlCommand
Dim parm As MySqlParameter
' Create the SelectCommand.
cmd = New MySqlCommand("SELECT * FROM mytable WHERE id=?id AND name=?name", conn)
cmd.Parameters.Add("?id", MySqlDbType.VarChar, 15)
cmd.Parameters.Add("?name", MySqlDbType.VarChar, 15)
da.SelectCommand = cmd
' Create the InsertCommand. put this in a loop
cmd = New MySqlCommand("INSERT INTO mytable (id,name) VALUES (?id, ?name)", conn)
cmd.Parameters.Add( "?id", MySqlDbType.VarChar, 15, "id" )
cmd.Parameters.Add( "?name", MySqlDbType.VarChar, 15, "name" )
da.InsertCommand = cmd


you can find more information about data adapter on this link[^].
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900