简体   繁体   中英

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

My SQL statement works fine without the delete statement which is my problem. I use 2 OleDbCommands to call the seperate queries. This is my current SQL statement in C#:

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

string newsql = "DELETE FROM Dryers WHERE [Batch number]='"+batchNumber+"'";

This my latest failed attempt in code:

        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 gives the following error:

Failed due toData type mismatch in criteria expression.

You can't do this in Access. You have to call two separate SQL strings.

Use two statements but wrap them in a transaction so it's a single unit of work.

BEGIN TRANSACTION
COMMIT

if you wanted to do it in C# then you would wrap your queries in a transaction scope.

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.
}

Here is a walkthrough from Microsoft about making the connection against an access database and querying using ADO.NET. https://msdn.microsoft.com/en-us/library/ms971485.aspx

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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