P
Paolo
I'm new to C# so apologies if this is a dumb question.
If I want to insert a new row into a SQLServer table I can have a method
something like this:
public void insertRow(int id, string description, datetime yearConstructed)
{
string sql = string.Format("Insert into <tableName>"+
"(idKey, makeDescription, yearBuilt) Values"+
"('{0}', '{1}', '{2}')", id, description, yearConstructed);
using(SqlCommand cmd = new SqlCommand(sql, this.sqlCn))
{
cmd.ExecuteNonQuery();
}
}
This is fine but hard codes column and table names and data parameters into
the method.
What I want to do is write a generalised Insertion method that can take any
number of column names and their associated data parameters and table name
whose signature looks something like this:
public void insertRow(string tableName, string[] columnNames, <a parameter
that can take varying numbers of different data types>)
and within the method iterate through the column names and data names/types
to build up the required SQL command.
In essence I'm looking to write reusable code. With my limited knowledge of
C# I'm not sure how to tackle this, especially how to pass a bunch of
differing data types to the method. I'd envisage using a Stringbuilder to
build up the first part of the Insertion command but am not sure how to get
the data names into the command i.e. the equivalents of id, description and
yearConstructed in the initial example.
All contributions gratefully accepted.
If I want to insert a new row into a SQLServer table I can have a method
something like this:
public void insertRow(int id, string description, datetime yearConstructed)
{
string sql = string.Format("Insert into <tableName>"+
"(idKey, makeDescription, yearBuilt) Values"+
"('{0}', '{1}', '{2}')", id, description, yearConstructed);
using(SqlCommand cmd = new SqlCommand(sql, this.sqlCn))
{
cmd.ExecuteNonQuery();
}
}
This is fine but hard codes column and table names and data parameters into
the method.
What I want to do is write a generalised Insertion method that can take any
number of column names and their associated data parameters and table name
whose signature looks something like this:
public void insertRow(string tableName, string[] columnNames, <a parameter
that can take varying numbers of different data types>)
and within the method iterate through the column names and data names/types
to build up the required SQL command.
In essence I'm looking to write reusable code. With my limited knowledge of
C# I'm not sure how to tackle this, especially how to pass a bunch of
differing data types to the method. I'd envisage using a Stringbuilder to
build up the first part of the Insertion command but am not sure how to get
the data names into the command i.e. the equivalents of id, description and
yearConstructed in the initial example.
All contributions gratefully accepted.