joe_pool_is
Well-known member
Ive got some code that works whenever I fill my SQL Server tables, but now that I am getting used to how to do this, my technique is starting to look like it does some unnecessary steps.
I have found that before I can call a SqlDataAdapters Update method after specifying an InsertCommand, I have to provide it with a Select statement and call the Fill method so that the Column Names are known whenever I try to populate fields for my InsertCommand.
After I call the SqlDataAdapters Fill method, I create a NewRow for the DataTable, and supply each Column Name with a Value.
Next, I create a new SqlCommand and add Parameter values to it.
After this, I assign this SqlCommand object to the SqlDataAdapters InsertCommand and call the SqlDataAdapters Update method.
Am I doing too many steps? It seems unnecessary to populate the Select statement and call the Fill method on the SqlDataAdapter first. It also seems like a waste of time to create a NewRow for the DataTable.
Like I said, this does work. Should I continue in this fashion, or is there a more streamlined technique?
I have found that before I can call a SqlDataAdapters Update method after specifying an InsertCommand, I have to provide it with a Select statement and call the Fill method so that the Column Names are known whenever I try to populate fields for my InsertCommand.
After I call the SqlDataAdapters Fill method, I create a NewRow for the DataTable, and supply each Column Name with a Value.
Next, I create a new SqlCommand and add Parameter values to it.
After this, I assign this SqlCommand object to the SqlDataAdapters InsertCommand and call the SqlDataAdapters Update method.
Am I doing too many steps? It seems unnecessary to populate the Select statement and call the Fill method on the SqlDataAdapter first. It also seems like a waste of time to create a NewRow for the DataTable.
Like I said, this does work. Should I continue in this fashion, or is there a more streamlined technique?
Code:
string select = string.Format("SELECT [Column1], [Column2], [Column3] " +
"FROM Table2 WHERE ([Column2={0})", strValue2);
string insert = "INSERT INTO Table2 ([Column1], [Column2], [Column3]) " +
"VALUES (@VAL1, @VAL2, @VAL3)";
SqlCommand cmd = new SqlCommand(select, m_db);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
try {
da.Fill(dt);
DataRow dr = dt.NewRow();
dr["Column1"] = strValue1;
dr["Column2"] = strValue2;
dr["Column3"] = strValue3;
cmd = new SqlCommand(insert, m_db);
cmd.Parameters.Add("@VAL1", SqlDbType.VarChar, 20).Value = strValue1;
cmd.Parameters.Add("@VAL2", SqlDbType.VarChar, 20).Value = strValue2;
cmd.Parameters.Add("@VAL3", SqlDbType.VarChar, 20).Value = strValue3;
da.InsertCommand = cmd;
int nCount = da.Update(dt);
if (nCount != 1) {
Console.WriteLine(string.Format("{0} records were affected.", nCount);
}
} catch (SqlException e) {
Console.WriteLine(e.Message);
} finally {
cmd.Dispose();
dt.Dispose();
da.Dispose();
}