将值插入数据库 [英] Inserting value into database

查看:73
本文介绍了将值插入数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将值插入到数据库中,但是当我的代码用作存储过程时,我的代码完全正常工作。我是trieng使用按钮单击来存储值。请告诉我们代码有什么问题。它没有显示任何错误或异常,但数据未在表格中更新。

I wanted to insert values into database but it is not working eventhough my code perfectly working when its used as stored procedure. I am trieng to use button click to store the value. Please tell whats wrong with the code. Its not showing any error or exception but data is not getting updated in the table.

protected void Button1_Click(object sender, EventArgs e)
{
        SqlConnection sqlConnection1 = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
        SqlCommand cmd = new SqlCommand();

        cmd.CommandText = "INSERT INTO sales(acnum, scripname, shares_bought) VALUES ('12', 'abcd', '20')";
        cmd.CommandType = CommandType.Text;
        cmd.Connection = sqlConnection1;
        sqlConnection1.Open();

        cmd.ExecuteNonQuery();
        sqlConnection1.Close();                                
}

推荐答案

强烈建议使用 SqlParametersCollection.Add [ ^ ]创建新 SqlCommand [ ^ ] 。 (可选)您可以使用 SqlParametersCollection.AddWithValue方法 [ ^ ]。



It's strongly recommended to use SqlParametersCollection.Add[^] method to create new SqlCommand[^]. Optionally, you can use SqlParametersCollection.AddWithValue method[^].

string commandText = "INSERT INTO sales(acnum, scripname, shares_bought) VALUES (@acnum, @scripname, @sbought)";
using (SqlConnection connection = new SqlConnection(connectionString))
{
    SqlCommand command = new SqlCommand(commandText, connection);
    command.Parameters.AddWithValue("@acnum", 12);
    command.Parameters.AddWithValue("@scripname", "abcd");
    command.Parameters.AddWithValue("@sbought", 20);

    try
    {
        connection.Open();
        Int32 rowsAffected = command.ExecuteNonQuery();
        Console.WriteLine("RowsAffected: {0}", rowsAffected);
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.Message);
    }
}


这篇关于将值插入数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆