我是 SQL 新手,在我的项目中,我试图从 DataBase 表中填充 DataSet,然后在 DataSet 中插入新行。完成此操作后,我再次使用 DataSet 数据填充数据库表。在填充之前,我正在清除或删除数据库表数据。好吧,我通过使用以下代码实现了这一点:
Database Table --> myTable
DataSet --> ds
按钮点击
string strQuery = "delete from [dbo].[myTable]"
SqlConnection conn = new SqlConnection(strConn);
SqlCommand cmd = new SqlCommand(strQuery, conn);
SqlCommand command;
SqlDataAdapter da = new SqlDataAdapter(cmd);
using (cmd)
{
using (conn)
{
conn.Open();
cmd.ExecuteNonQuery(); //deleting database table data
foreach (DataRow dr in ds.Tables[0].Rows) //Inserting new data into the Database table
{
command = new SqlCommand(InsertQuery, conn);
command.ExecuteNonQuery();
}
conn.Close();
}
}
上面的代码工作正常,但是当command
sqlCommand 中有任何异常时,它会完全删除数据库表而不填充 DataSet。有什么建议可以修改此代码吗?请帮忙。
更新:
string strQuery = "delete from [dbo].[myTable]";
using (SqlCommand cmd = new SqlCommand(strQuery, conn))
{
using (SqlCommand cmdReset = new SqlCommand("DBCC CHECKIDENT('myTable', RESEED, 0)", conn))
{
SqlDataAdapter da = new SqlDataAdapter(cmd);
conn.Open();
SqlTransaction sqlTransaction = conn.BeginTransaction();
cmd.Transaction = sqlTransaction;
try
{
cmd.ExecuteNonQuery(); //deleting database table data
cmdReset.ExecuteNonQuery(); //Resetting Identity of first column
foreach (DataRow dr in ds.Tables[0].Rows) //Inserting new data into the Database table
{
command = new SqlCommand(query.createDoctorRow(InsertQuery, conn);
command.ExecuteNonQuery();
}
sqlTransaction.Commit();
conn.Close();
}
catch (Exception e)
{
sqlTransaction.Rollback();
/*ERROR*/ throw;
}
}
}
错误 --> “当分配给命令的连接处于挂起的本地事务中时,ExecuteNonQuery 要求命令具有事务。命令的事务属性尚未初始化。”