I have a disconnected dataTable
that contains a few records.
I am using the following function to get the dataTable
.
static System.Data.DataTable ReadSetUpTable(string queryStr,SqlConnection sc)
{
try
{
var command = new SqlCommand()
{Connection = sc, CommandText = queryStr};
var dataAdapter = new SqlDataAdapter() {SelectCommand = command};
var dataTable = new System.Data.DataTable();
dataAdapter.Fill(dataTable);
return dataTable;
}
catch (Exception)
{
throw;
}
}
No issues so far.
What I want to know is if there's an easy to populate this dataTable
into another schema using a different connection string.
For the sake of this post, assume that there is a table with two columns
Create Table Student(StudentId NUMBER(6), StudentName varchar2(50));
I wish to fill this table with the dataTable
that I have in the above code.
I could do it using a command Object and an insert statement. For example this code:
static int LoadDataTable(OracleConnection oc, System.Data.DataTable dataTable)
{
try
{
var command =
new OracleCommand
{
CommandText = "INSERT INTO STUDENT (STUDENTID, STUDENTNAME) VALUES(:studentid, :studentname)",
CommandType = CommandType.TableDirect,
Connection = oc
};
var op1 =
new OracleParameter
{
ParameterName = "StudentId",
Size = 6,
OracleDbType = OracleDbType.Int32,
Direction = System.Data.ParameterDirection.Input
};
command.Parameters.Add(op1);
var op2 =
new OracleParameter
{
ParameterName = "studentName",
OracleDbType = OracleDbType.Varchar2,
Size = 50,
Direction = System.Data.ParameterDirection.Input
};
command.Parameters.Add(op2);
/*
foreach (var row in dataTable.Rows)
{
op1.Value = int.Parse(row[0].ToString());
op2.Value = row[1].ToString();
command.ExecuteNonQuery();
}*/
foreach (System.Data.DataRow row in dataTable.Rows)
{
row.SetAdded();
}
var dataAdapter = new OracleDataAdapter() {InsertCommand = command};
dataAdapter.Update(dataTable); //This updates the table, but all column values are NULL.
}
catch(Exception)
{
throw;
}
}
Is there a quicker and easier way where I will not have to loop through the records?