不存储在数据库中的新行

时间:2014-07-07 13:17:57

标签: c# sql sql-server database

我正在使用以下代码将表单输入中的数据存储到数据库中。

代码似乎成功执行,消息框指出一行已受影响(正如预期的那样)。

当我查看visual studio中的数据源窗口时,数据集中没有保存新行。

保存的新行在哪里?我如何将它们提交到数据库?

提前致谢。

    private void btnSavePublication_Click(object sender, EventArgs e)
    {
        // get the inputs
        int pubID = Convert.ToInt32(txtPubID.Text);
        string pubTitle = txtTitle.Text;
        long pubBarcode = Convert.ToInt64(txtBarcode.Text);
        string pubDate = txtRecievedDate.Text;
        decimal pubPrice = Convert.ToDecimal(txtPrice.Text);

        // retrieve the connection string
        string myConnectionString = Properties.Settings.Default.Database1ConnectionString;

        // open the connection to the database
        SqlConnection connection = new SqlConnection();
        connection.ConnectionString = myConnectionString;

        // create a SQL command to update the table
        SqlCommand command = new SqlCommand();
        command.Connection = connection;

        // set up the paramaters
        command.Parameters.AddWithValue("@PublicationID", pubID);
        command.Parameters.AddWithValue("@PublicationTitle", pubTitle);
        command.Parameters.AddWithValue("@PublicationBarcode", pubBarcode);
        command.Parameters.AddWithValue("@PublicationDate", pubDate);// TODO parse the date
        command.Parameters.AddWithValue("@PublicationPrice",pubPrice);

        // create the SQL query
        command.CommandText = "INSERT INTO Publication (PublicationID, PublicationTitle, " + 
                                                        "PublicationBarcode, PublicationDate, "+ 
                                                        "PublicationPrice)" +
                              "VALUES ( @PublicationID, @PublicationTitle, @PublicationBarcode, " + 
                              "@PublicationDate, @PublicationPrice)";

        // run the query (hopefully)
        try {
            connection.Open();
            int rowsAffected = command.ExecuteNonQuery();
            MessageBox.Show( rowsAffected + " rows affected");

        }
        catch {
            MessageBox.Show("Wakka wakka");
        }
        finally {
            connection.Close();
        }
    }

编辑:这是我的连接字符串 -

"Data Source=(LocalDB)\\v11.0;AttachDbFilename=|DataDirectory|\\Database1.mdf;Integr" +
        "ated Security=True;Connect Timeout=30"

0 个答案:

没有答案