I know there are questions like this already, but I've combined all the common code to the answers and still am getting no success, so here I am.
Here's the deal. I have a block of code using SqlDataAdapter.Update to insert new rows into an existing table...
string command = "SELECT * FROM " + tableName;
// Initialize connection
if (oConn == null)
{
oConn = new SqlConnection(mainConnStr);
}
sCmd = new SqlCommand(command, oConn);
sCmd.CommandText = command;
SqlDataAdapter sDA = new SqlDataAdapter(sCmd);
DataSet ds = new DataSet();
oConn.Open();
sDA.Fill(ds, tableName);
oConn.Close();
DataTable dt = ds.Tables[tableName];
//Add each row.
for (int i = 0; i < queryResult.Rows.Count; i++)
{
dt.ImportRow(queryResult.Rows[i]);
}
// Handle the command building for the table update.
SqlCommandBuilder sCB = new SqlCommandBuilder(sDA);
oConn.Open();
sDA.Update(ds, tableName);
oConn.Close();
As mentioned, this works fine. However, if I try very similar code with a two-column test table (testInt, an int non-null; and testSTring, a varchar(50), null-allowed)...
private static void Main(string[] args)
{
SqlConnection = /* Build connection */
string sqlQuery = "SELECT * FROM TestTable WHERE 0 = 1";
SqlDataAdapter sDA = new SqlDataAdapter(sqlQuery, conn);
DataSet dataSet = new DataSet();
conn.Open();
sDA.Fill(dataSet);
conn.Close();
DataRow newRow = dataSet.Tables[0].NewRow();
newRow["testInt"] = 12;
SqlCommandBuilder cb = new SqlCommandBuilder(sDA);
conn.Open();
sDA.Update(dataSet);
conn.Close();
}
This code does nothing, and I can't figure out what in the world the difference is. (I should note that I've also tried using ImportRow instead of the NewRow technique.) Even when I try this block of code with the same tables as the first block (the working block), it still won't u开发者_JAVA技巧pdate the data.
Therefore, my question is: What fine details must be accounted for when using SqlDataAdapter.Update?
Thanks.
-F
You have to add the row to the DataSet
DataRow newRow = dataSet.Tables[0].NewRow(); // this doesn't add a new row to the data set
dataSet.Tables[0].Rows.Add(newRow); // you have to call this after
精彩评论