使用Visual C#2010使用SQL命令不会将数据插入数据库

时间:2013-02-10 10:46:51

标签: c# sql sql-server connection

private void button1_Click(object sender, EventArgs e)
{
        SqlConnection con = new SqlConnection();

        con.ConnectionString = @"Data Source=YUVV-PC\SQLEXPRESS;Initial Catalog=barcode;Integrated Security=True";
        con.Open();

        //MessageBox.Show("connection open");

        SqlDataAdapter ada = new SqlDataAdapter();
        //ada.SelectCommand = new SqlCommand("select * from barcode", con);
        ada.MissingSchemaAction = MissingSchemaAction.AddWithKey;
        ada.InsertCommand = new SqlCommand("INSERT INTO barcode (bcd) " +
    "VALUES (@bcd)", con);
        ada.InsertCommand.Parameters.Add("@bcd", SqlDbType.NChar, 20,"bcd").Value = textBox1.Text;
        ada.SelectCommand = new SqlCommand("select bcd from barcode", con);

        DataSet ds = new DataSet();
        ada.Fill(ds, "barcode");
        dataGridView1.DataSource = ds.Tables[0].DefaultView;
    }

1 个答案:

答案 0 :(得分:1)

您有以下2个修改代码的选项(con.Open()之后):

ada.InsertCommand.Parameters.Add("@bcd", SqlDbType.NChar, 20,"bcd").Value = textBox1.Text;
//add this line
//without it you are never executing your `InsertCommand`.
ada.InsertCommand.ExecuteNonQuery();

ada.SelectCommand = new SqlCommand("select bcd from barcode", con);
...

或者您也可以使用SqlCommand,如此:

using (var cmd = new SqlCommand("INSERT INTO barcode (bcd) VALUES (@bcd)", con))
{
    cmd.CommandType = CommandType.Text;
    cmd.Parameters.Add("@bcd", SqlDbType.NChar, 20,"bcd").Value = textBox1.Text;
    cmd.ExecuteNonQuery();
}

SqlDataAdapter ada = new SqlDataAdapter();
//ada.SelectCommand = new SqlCommand("select * from barcode", con);
ada.MissingSchemaAction = MissingSchemaAction.AddWithKey;

ada.SelectCommand = new SqlCommand("select bcd from barcode", con);

DataSet ds = new DataSet();
ada.Fill(ds, "barcode");
dataGridView1.DataSource = ds.Tables[0].DefaultView;

我还建议在usingSqlConnection个实例周围使用SqlDataAdapter语句,以确保正确处理所有资源。