我知道這樣的問題已經存在,但我已將所有常見代碼結合到答案中,但仍然沒有取得成功,所以我就是這樣。SqlDataAdapter.Update:是否存在SQL版本要求?
這是交易。我有一個代碼塊使用SqlDataAdapter.Update插入新行到現有的表...
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();
如上所述,這工作正常。但是,如果我試圖用一個兩列測試表(testInt,一個int非空;和的TestString,一個varchar(50),空允許的)非常相似的代碼...
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();
}
此代碼沒有什麼,我無法弄清楚世界上的差別是什麼。 (我應該注意,我也嘗試使用ImportRow而不是NewRow技術。)即使當我嘗試使用與第一個塊(工作塊)相同的表的代碼塊時,它仍然不會更新數據。
因此,我的問題是:使用SqlDataAdapter.Update時必須考慮哪些細節?
謝謝。
-F
也許你需要返回一些數據,然後才能更新呢? – ChrisBint
我假設這只是示例代碼,而不是你如何編寫真實的東西,但正如頭一樣,'SqlCommandBuilde,'DataSet','DataTable'和你的'SqlConnection'都實現了'IDisposable',並且應該有他們調用了Dispose()方法。 – pstrjds