繁体   English   中英

如何从表中删除一行并将其通过SQL语句插入另一行?

[英]How can I remove one row from a table and insert it into another via a SQL statement?

没有删除语句,这是我的问题,我的SQL语句工作正常。 我使用2个OleDbCommands调用单独的查询。 这是我当前在C#中使用的SQL语句:

string mysql = "Insert Into Completed([Batch number], [Product], [Weight]) VALUES('" + batchNumber + "','" + product + "','" + weight + "')"; 

字符串newsql =“从干燥机中删除[批次号] ='” + batchNumber +“'”;

这是我最近在代码中失败的尝试:

        if (conn.State == ConnectionState.Open)
        {

            try
            {
                using (System.Transactions.TransactionScope tScope = new TransactionScope())
                {
                    string batchNumber = txtBatchNumber3.Text.ToString();
                    string product = txtProduct3.Text.ToString();
                    string weight = txtWeight3.Text.ToString();

                    string mysql = "Insert Into Packing([Batch number], [Product], [Weight]) VALUES('" + batchNumber + "','" + product + "','" + weight + "') ";
                    string newsql = "DELETE * FROM Dryers WHERE [Batch number]='" + batchNumber + "'";

                    OleDbCommand cmd = new OleDbCommand(mysql, conn);
                    cmd.ExecuteNonQuery();
                    OleDbCommand cmd2 = new OleDbCommand(newsql, conn);
                    cmd2.ExecuteNonQuery();

                    tScope.Complete();

                }


                MessageBox.Show("Data saved successfuly...!");
                this.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show("Failed due to" + ex.Message);
            }
            finally
            {
                conn.Close();                    
            }
            }                
        else
        {
            MessageBox.Show("Connection Failed");
        }

    }
    }
}

VS2012出现以下错误:

由于条件表达式中的数据类型不匹配而失败。

您无法在Access中执行此操作。 您必须调用两个单独的SQL字符串。

使用两个语句,但是将它们包装在一个事务中,因此它是一个工作单元。

BEGIN TRANSACTION
COMMIT

如果您想使用C#进行操作,则可以将查询包装在事务范围中。

using (System.Transactions.TransactionScope tScope = new TransactionScope())
{
    //do work here
    //if work is completed
    tScope.Complete();

    //else do nothing the using statement will dispose the scope and rollback your changes.
}

这是Microsoft的演练,内容涉及如何针对访问数据库建立连接并使用ADO.NET查询。 https://msdn.microsoft.com/en-us/library/ms971485.aspx

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM