473,385 Members | 2,180 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,385 software developers and data experts.

Which one is a better [InsertCommand]...

RP
>From the below given codes used to insert a record in a table, which
code is well-optimized and must be used. Please also let me know why
it is better.

=======[ CODE 1 ]===========================================
public Int32 InsertNewRecord(string myQuery)
{
objModCon.OpenConnection();
SqlCommand cmdInsert = new SqlCommand(myQuery,
objModCon.myCN);
try
{
Int32 RecordsAffected = cmdInsert.ExecuteNonQuery();
return RecordsAffected;
}
catch (Exception ex)
{
MessageBox.Show("Routine: ModReUsable-
InsertNewRecord(" + myQuery + ") " + ex.ToString(), "Error:",
MessageBoxButtons.OK, MessageBoxIcon.Error);
return 0;
}
finally
{
cmdInsert.Dispose();
objModCon.CloseConnection();
}
}
========[ CODE 2 ]==================================================
public static OleDbDataAdapter CreateCustomerAdapter(
OleDbConnection connection)
{
OleDbDataAdapter adapter = new OleDbDataAdapter();
OleDbCommand command;

// Create the SelectCommand.
command = new OleDbCommand("SELECT CustomerID FROM Customers " +
"WHERE Country = ? AND City = ?", connection);

command.Parameters.Add("Country", OleDbType.VarChar, 15);
command.Parameters.Add("City", OleDbType.VarChar, 15);

adapter.SelectCommand = command;

// Create the InsertCommand.
command = new OleDbCommand(
"INSERT INTO Customers (CustomerID, CompanyName) " +
"VALUES (?, ?)", connection);

command.Parameters.Add(
"CustomerID", OleDbType.Char, 5, "CustomerID");
command.Parameters.Add(
"CompanyName", OleDbType.VarChar, 40, "CompanyName");

adapter.InsertCommand = command;
return adapter;
}
================================================== ================================================== =

Oct 12 '07 #1
2 1572
RP wrote:
>>From the below given codes used to insert a record in a table, which
code is well-optimized and must be used. Please also let me know why
it is better.
Neither.

For only the purpose of inserting a record, just take out the code that
creates the insert command from the second piece of code, and skip the
data adapter entirely. Use the ExecuteNonQuery method to run it, just
like in the first piece of code.

Reasons:

There is no need for a data adapter to insert a record. You only need
the command.

You should always use parameters with your command:

- Putting the values directly in the query is difficult without exposing
your code to the risk of SQL injection.

- The database can cache the execution plan for parameterised queries,
as the query doesn't change when the values change. (Not really
important for just an insert, but relevant for more complex queries.)

--
Göran Andersson
_____
http://www.guffa.com
Oct 12 '07 #2
RP,

This question sounds for me a little bit the same as asking "what is better
a plane or a car".

Beside that both codes are not quiet as good as it can be for several
reasons. Are you using C# 2003 by the way?

Cor
"RP" <rp*********@gmail.comschreef in bericht
news:11*********************@i13g2000prf.googlegro ups.com...
From the below given codes used to insert a record in a table, which
code is well-optimized and must be used. Please also let me know why
it is better.

=======[ CODE 1 ]===========================================
public Int32 InsertNewRecord(string myQuery)
{
objModCon.OpenConnection();
SqlCommand cmdInsert = new SqlCommand(myQuery,
objModCon.myCN);
try
{
Int32 RecordsAffected = cmdInsert.ExecuteNonQuery();
return RecordsAffected;
}
catch (Exception ex)
{
MessageBox.Show("Routine: ModReUsable-
InsertNewRecord(" + myQuery + ") " + ex.ToString(), "Error:",
MessageBoxButtons.OK, MessageBoxIcon.Error);
return 0;
}
finally
{
cmdInsert.Dispose();
objModCon.CloseConnection();
}
}
========[ CODE 2 ]==================================================
public static OleDbDataAdapter CreateCustomerAdapter(
OleDbConnection connection)
{
OleDbDataAdapter adapter = new OleDbDataAdapter();
OleDbCommand command;

// Create the SelectCommand.
command = new OleDbCommand("SELECT CustomerID FROM Customers " +
"WHERE Country = ? AND City = ?", connection);

command.Parameters.Add("Country", OleDbType.VarChar, 15);
command.Parameters.Add("City", OleDbType.VarChar, 15);

adapter.SelectCommand = command;

// Create the InsertCommand.
command = new OleDbCommand(
"INSERT INTO Customers (CustomerID, CompanyName) " +
"VALUES (?, ?)", connection);

command.Parameters.Add(
"CustomerID", OleDbType.Char, 5, "CustomerID");
command.Parameters.Add(
"CompanyName", OleDbType.VarChar, 40, "CompanyName");

adapter.InsertCommand = command;
return adapter;
}
================================================== ================================================== =
Oct 16 '07 #3

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

Similar topics

0
by: hamid S | last post by:
Hi, I am new to ADO.Net and I am getting system error when I try to issue the System Error and sqlDataAdapter.InsertCommand.ExecuteNonQuery to update the database. What could be wrong. Please...
5
by: Darryn Ross | last post by:
Hi, I am running an insert statement into an access database, but i don't want to add information to every column in my table... when i run my insertcommand the following exception is thrown......
1
by: Luboą ©lapák | last post by:
Hi, I need define InsertCommand in SQLDataAdapter, but I don't know how. Please Help me. I don't know the format of InsertCommand. Thanks
3
by: Jon S via DotNetMonster.com | last post by:
Hi all, I'm having a problem updating a simple change I've made to a Access 2000 table through databinding. The error I get is : An unhandled exception of type...
1
by: zoneal | last post by:
I retrieved the following function from VB.NET help and added a few statements for updating the datasource. But, it does not actually commence the InsertCommand property of the DataAdapter in order...
1
by: Jim | last post by:
Using VS 2005. I have bound fields on a form bound to a dataset(s) and I want to add various data elements to fields in the DB that are not comming from bound fields. This is what I have resorted...
3
by: Rich | last post by:
What is the diffeence bewtween a dataAdapter.InsertCommand and dataAdapter.SelectCommand (and dataAdapter.UpdateCommand for that matter)? Dim da As SqlDataAdapter conn.Open da.SelectCommand =...
2
Elnath
by: Elnath | last post by:
im connecting to a DataBase tru ODBC, i need to insert new records (rows) therefore i want the InsertCommand to be generated by my CommbadBuilder. This solution however is aint working, the...
2
by: Cirene | last post by:
In my HTML view of my ASPX page how do I use the NOW() function for the InsertCommand? This doesn't seem to work... Code snippet: <asp:SqlDataSource ID="sdsPress" runat="server"...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 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 former...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...

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.