Click here to Skip to main content
15,891,513 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
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.
C#
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();                                
}
Posted
Updated 10-Sep-15 4:05am
v2
Comments
ZurdoDev 10-Sep-15 9:39am    
You're probably pointing to a different database. Just debug the code and see what ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString is.
Member 11949886 11-Sep-15 1:42am    
its allright sir, I checked
ZurdoDev 11-Sep-15 7:08am    
Then if there is no error the insert is happening.
Maciej Los 10-Sep-15 15:47pm    
Does acnum and shares_bought is numeric data field?
Member 11949886 11-Sep-15 1:38am    
yes sir

1 solution

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

C#
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);
    }
}
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900