Search code examples
c#sqlconnectionsqlcommand

Sql excxeption was unhandled by user code,Incorrect syntax near ','


I really dont know what is wrong with my Insert statement, it compains about unhandled user code. My insert on cmd looks fine as compared to other tutorials online.

public void retrieveData()
{
    SqlConnection(ConfigurationManager.ConnectionStrings[sqlconnectiostring].ToString())
    SqlConnection conn = new SqlConnection();

    try
    {
        using (conn = new SqlConnection(sqlconnectiostring))
        {
            conn.Open();
            SqlCommand cmd = new SqlCommand("INSERT INTO FRUITSPRODUCT(@PRODUCTNAME,@PRODUCTTYPE,@Total) VALUES (@PRODUCTNAME,@PRODUCTTYPE,@Total)",conn);
            cmd.Parameters.AddWithValue("@PRODUCTNAME","atlegang");
            cmd.Parameters.AddWithValue("@PRODUCTTYPE","baby");
            cmd.Parameters.AddWithValue("@Total","10");
            cmd.ExecuteNonQuery();
        }
    }
    catch (Exception ex)
    {
        throw ex;
    }
    finally
    {
        if (conn != null)
        {
            conn.Close();
        }
    }
}

Solution

  • This is your insert-sql:

    INSERT INTO FRUITSPRODUCT(@PRODUCTNAME,@PRODUCTTYPE,@Total) VALUES (,,)
    

    This is the correct syntax:

    INSERT INTO FRUITSPRODUCT(PRODUCTNAME,PRODUCTTYPE,Total) VALUES (@PRODUCTNAME,@PRODUCTTYPE,@Total)