你做的参数完全错误,因为你唯一的事情catch
就是sqlTrans.Rollback();
你永远看不到你得到的错误,我要改变的第一件事就是让那个 catch
catch (System.Data.SqlClient.SqlException)
{
sqlTrans.Rollback();
throw;
}
所以你现在可以看到错误发生了。
下一个问题是,如果表有任何外键约束,您TRUNCATE TABLE
将失败,如果失败,您可以简单地将其替换为
string delCmdTxt = "delete from PLODINY";
SqlCommand cmdDel = spojeni.CreateCommand();
cmdDel.CommandText = delCmdTxt;
cmdDel.Transaction = sqlTrans;
cmdDel.ExecuteNonQuery();
至于为什么您的插入不起作用,您正在处理 for 循环的每个实例的命令,您还尝试每次重新添加参数,将该循环重新格式化为以下
string insert_sql = "INSERT INTO PLODINY(PLODINA,CENAZAQ,MJ)VALUES(@PLODINA,@CENAZAQ,@MJ)";
using(SqlCommand sqlcom = spojeni.CreateCommand())
{
sqlcom.CommandText = insert_sql;
sqlcom.Transaction = sqlTrans;
sqlcom.Parameters.Add("@PLODINA", SqlDbType.NVarChar); //Replace with whatever the correct datatypes are
sqlcom.Parameters.Add("@CENAZAQ", SqlDbType.NVarChar);
sqlcom.Parameters.Add("@MJ", SqlDbType.NVarChar);
foreach (DataGridViewRow row in dataGridView1.Rows)
{
sqlcom.Parameters["@PLODINA"] = row.Cells["PLODINA"].Value;
sqlcom.Parameters["@CENAZAQ"] = row.Cells["CENAZAQ"].Value;
sqlcom.Parameters["@MJ"] = row.Cells["MJ"].Value;
sqlcom.ExecuteNonQuery();
}
}
sqlTrans.Commit();
但是,您的代码可以做得更好,如果您的 DataGridView 通过绑定由 DataTable 支持,您可以改用 SqlTableAdapter,假设您从数据库加载表,将其显示在网格上,然后您想推回更新信息。使用 DataTable 它会很简单
private string _getDataQuery = "select PLODINA, CENAZAQ, MJ from PLODINY";
public void GetData(DataTable data)
{
//You do not need to call open here as SqlDataAdapter does it for you internally.
using(var spojeni = new SqlConnection(GetConnectionString())
using(var adapter = new SqlDataAdapter(_getDataQuery, spojeni)
{
data.Clear();
adapter.Fill(data);
}
}
public void UpdateData(DataTable data)
{
using(var spojeni = new SqlConnection(GetConnectionString())
using(var adapter = new SqlDataAdapter(_getDataQuery, spojeni)
using(var commandBuilder = new SqlCommandBuilder(adapter)
{
//This may or may not be nessesary for spojeni.BeginTransaction()
spojeni.Open();
using(var sqlTrans = spojeni.BeginTransaction())
{
adapter.SelectCommand.Transaction = sqlTrans;
adapter.UpdateCommand = commandBuilder.GetUpdateCommand();
adapter.UpdateCommand.Transaction = sqlTrans;
adapter.DeleteCommand = commandBuilder.GetDeleteCommand();
adapter.DeleteCommand.Transaction = sqlTrans;
adapter.InsertCommand = commandBuilder.GetInsertCommand()
adapter.InsertCommand.Transaction = sqlTrans;
try
{
adapter.Update(data);
sqlTrans.Commit();
}
catch
{
sqlTrans.Rollback();
throw;
}
}
}
}