Problem inserting data into database C# SQL!

Csharp , ASP.NET , .NET 4.0 , SQL Rāwalpindi, Pakistan
  • 10 years ago

    Hi All,

    I am trying to insert data into my database, the query is running smooth, that is without any error but the problem is that the data isn't being inserted and table remains empty.

    Here is the code i'm using: [C#] string sConnectionString = ConfigurationManager.ConnectionStrings["StagingAreaDB.Properties.Settings.StagingAreaDBConnectionString"].ConnectionString;

            SqlConnection cSqlConnection = new SqlConnection(sConnectionString);
            SqlCommand cSqlCommand = new SqlCommand();
    
    
            cSqlCommand.CommandText = "insert into CropData(PesticideUsed,PesticideSprayDate, PesticideDosage, CLCV, PlantHeight) Values ('Triazophos' , '11/09/2004' , '459 grams' , '46 Medium' , '46 foot');";
            cSqlCommand.CommandType = CommandType.Text;
            cSqlCommand.Connection = cSqlConnection;
    
            cSqlConnection.Open();
            try
            {
                cSqlCommand.ExecuteNonQuery();
            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.StackTrace.ToString());
            }
            finally
            {
                cSqlConnection.Close();
            }
    

    Can anybody tell me that where the probelm? Thanks in advance.

  • 10 years ago

    What does the table look like? Also are there any unique indexes on the table? If I were a betting man I would guess that you have a unique index on your database and the row your trying to insert is a duplicate. Normally that would produce an error, but if your index has the flag IGNOREDUPKEY then it would throw your row away and return like everything is ok. (which appears to be what is occuring.)

  • 10 years ago

    This time I created a new project with just one table in database having 3 cloumns(all varchar(50) and nullable). And used this code, but still database is empty and there isn't a single row in Table1. By the way I'm using Visual Studio 2010.

            string constr = ConfigurationManager.ConnectionStrings["TestConnectionString"].ConnectionString;
            string sql = "INSERT INTO Table1 VALUES('110','Mohsin Ali','BS(CS)')";
            SqlConnection conn = new SqlConnection(constr);
            SqlCommand com = new SqlCommand(sql, conn);
            conn.Open();
            com.ExecuteNonQuery();
            conn.Close();
    

Post a reply

Enter your message below

Sign in or Join us (it's free).

Contribute

Why not write for us? Or you could submit an event or a user group in your area. Alternatively just tell us what you think!

Our tools

We've got automatic conversion tools to convert C# to VB.NET, VB.NET to C#. Also you can compress javascript and compress css and generate sql connection strings.

“The generation of random numbers is too important to be left to chance.” - Robert R. Coveyou