0

您好我正在尝试执行以下操作

  1. 从表 X 中删除所有内容
  2. 将所需值插入表 X

我认为 T-SQL 将是实现这一目标的方法,因为当 INSERT 命令中出现问题时,所有内容都将被删除。

但是这段代码什么都不做,它不插入或删除数据。有人可以帮我解决这个问题吗?

spojeni.Open();
SqlTransaction sqlTrans = spojeni.BeginTransaction();
try
{
    string delCmdTxt = "TRUNCATE TABLE PLODINY";
    SqlCommand cmdDel = spojeni.CreateCommand();
    cmdDel.CommandText = delCmdTxt;
    cmdDel.Transaction = sqlTrans;
    cmdDel.ExecuteNonQuery();

    string insert_sql = 
        "INSERT INTO PLODINY(PLODINA,CENAZAQ,MJ)VALUES(@PLODINA,@CENAZAQ,@MJ)";
    SqlCommand sqlcom = spojeni.CreateCommand();
    sqlcom.CommandText = insert_sql;
    sqlcom.Transaction = sqlTrans;

    foreach (DataGridViewRow row in dataGridView1.Rows)
    {
        sqlcom.Parameters.AddWithValue("@PLODINA", row.Cells["PLODINA"].Value);
        sqlcom.Parameters.AddWithValue("@CENAZAQ", row.Cells["CENAZAQ"].Value);
        sqlcom.Parameters.AddWithValue("@MJ", row.Cells["MJ"].Value);

        sqlcom.ExecuteNonQuery();
        sqlcom.Dispose();
    }
    sqlTrans.Commit();
}
catch (System.Data.SqlClient.SqlException)
{
    sqlTrans.Rollback();
}
finally
{
    spojeni.Close();
    spojeni.Dispose();
}
this.Close();
4

3 回答 3

3

你的问题在你的foreach循环中。您需要事先定义参数,并且在完成所有操作之前不要释放命令对象。您还可以使用Where扩展方法从数据源中过滤掉任何无效行,因为它是一个 UI 元素。

string insert_sql = "INSERT INTO PLODINY(PLODINA,CENAZAQ,MJ)VALUES(@PLODINA,@CENAZAQ,@MJ)";
SqlCommand sqlcom = spojeni.CreateCommand();
sqlcom.CommandText = insert_sql;
sqlcom.Transaction = sqlTrans;
sqlcom.Parameters.Add("@PLODINA");
sqlcom.Parameters.Add("@CENAZAQ");
sqlcom.Parameters.Add("@MJ");

// some validation - add what you need.
var validRows = dataGridView1.Rows.Cast<DataGridViewRow>()
  .Where(row => row.Cells["PLODINA"].Value != null);

foreach (DataGridViewRow row in validRows)
{
    sqlcom.Parameters[0].Value = row.Cells["PLODINA"].Value;
    sqlcom.Parameters[1].Value = row.Cells["CENAZAQ"].Value;
    sqlcom.Parameters[2].Value = row.Cells["MJ"].Value;
    sqlcom.ExecuteNonQuery();
}

sqlTrans.Commit();
sqlcom.Dispose();
于 2013-11-09T22:27:17.267 回答
2

你做的参数完全错误,因为你唯一的事情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;
            }
        }
    }
}
于 2013-11-09T22:30:32.697 回答
2

截断表仅在表没有外键约束时才有效......它可能在那里失败,然后在 catch 语句中回滚事务......

而不是截断尝试从表中删除,看看是否可以修复它......

于 2013-11-09T22:25:45.907 回答