我使用以下代码将新行插入现有数据库表:
string strSQL2= "SELECT * FROM Staff";
SqlAdapter dataAdapter = new SqlDataAdapter(strSQL2, conString);
Dataset ds = new DataSet();
dataAdapter.Fill(ds);
DataRow newRow = ds.Tables[0].NewRow();
newRow["firstName"] = "Michael";
newRow["lastName"] = "Jackson";
newRow["username"] = "Michi";
newRow["admin"] = "0";
ds.Tables[0].Rows.Add(newRow);
var cmb = new SqlCommandBuilder(dataAdapter);
dataAdapter.Update(ds);
该代码旨在更新原始数据库,但事实并非如此。我没有得到任何错误。在SQL事件探查器中,我没有看到任何收到的命令。可能是什么问题?
答案 0 :(得分:1)
为什么不尝试更传统?:
private void InsertStaff()
{
string query = "INSERT INTO Staff (firstname, lastname, username, admin) VALUES (@firstname, @lastname, @username, 0)";
SqlParameter[] parameters = new SqlParameter[3];
parameters[0] = new SqlParameter("@firstname", SqlDbType.Varchar).Value = @firstname;
parameters[1] = new SqlParameter("@lastname", SqlDbType.Varchar).Value = @lastname;
parameters[2] = new SqlParameter("@username", SqlDbType.Varchar).Value = @username;
ExecuteNonQuery(query, parameters);
}
private void ExecuteNonQuery(string query, SqlParameter[] parametros)
{
var conn = new SqlConnection("Data Source=" + Server + ";Initial Catalog=" + Database + ";User Id=" + Username + ";Password=" + Password + ";");
try
{
conn.Open();
SqlCommand command = conn.CreateCommand();
command.CommandText = query;
foreach (SqlParameter p in parametros)
{
command.Parameters.Add(p);
}
command.ExecuteNonQuery();
}
catch (Exception)
{
throw;
}
finally
{
conn.Dispose();
conn.Close();
}
}