Single Row Insert

  • Thread starter Thread starter Greif
  • Start date Start date
G

Greif

I've written the following function to insert a single row
into a database. Here is the code:

public virtual int singleInsert(string tableName, params
IDbDataParameter[] values)
{
if(ConnectionString == "" || ConnectionString.Length == 0)
throw new InvalidOperationException("The connection
string is not set. Set the 'ConnectionString' member.");

if(values == null || values.Length == 0)
throw new ArgumentNullException("values", "The values
array was null or empty. You must pass value(s) to be
inserted.");

DataSet ds = new DataSet(tableName);
// returns a data-provider specific dataAdapter
IDbDataAdapter dataAdapter = GetDataAdapter(tableName,
ConnectionString);
// set the DA's insertCommand object using a
data-provider specific CommandBuilder
dataAdapter.InsertCommand = GetInsertCommand(dataAdapter);
dataAdapter.FillSchema(ds, SchemaType.Source);
DataRow newRow = ds.Tables["Table"].NewRow();

foreach(IDbDataParameter param in values)
{
if
(ds.Tables["Table"].Columns.Contains(param.ParameterName))
newRow[param.ParameterName] = param.Value;
}

ds.Tables["Table"].Rows.Add(newRow);
return dataAdapter.Update(ds);
}

A couple of questions ...
1 - How does the code look as far as scaling goes? Are
there any table locks occuring? (DataTable.NewRow()??)
2 - Any comments or suggestions on the code?
 
Hi,

A couple of questions ...
1 - How does the code look as far as scaling goes? Are
there any table locks occuring? (DataTable.NewRow()??)

Table locks in your code? DataTable (as almosty every .net class) is not
thread safe, thus it doesn't cretate any lock.
2 - Any comments or suggestions on the code?

Yeah.
a) Create a strong typed dataset instead of retrieving schema for every
insert - it awfully slows down your code.
b) invoke insert command directly (not by using
DataSets/DataTables/DataAdapters).

HTH,
 
Back
Top