简体   繁体   中英

Passing values from variables to Insert query in C#, ASP.NET for SQL Server database

I am using jQuery to post back values and its successfully posting back to server I checked with Mozilla FireBug. I am using these values in the insert query in .CS file to insert data in a table. The same query runs successfully in SQL Server Management Studio but when I use this query in .CS file it's not running.

Here is my code:

public static bool SaveCell(string row, string column)
{
    var con = new SqlConnection("Data Source=local;Initial Catalog=Test;Integrated Security=True");

    using (con)
    using (var command = new SqlCommand("Insert into Match_Subcategory_BusinessSector5(SubCategoryID, BusinessSector5ID)"+
           "Values("+
           "(Select [SubCategory].ID from SubCategory where Kategorie = '@SubCategory')," +
           "(SELECT [BusinessSector5].ID FROM BusinessSector5 where Description_DE = '@BusinessSector5'));",con))
    {
        command.Parameters.AddWithValue("@BusinessSector5", row);
        command.Parameters.AddWithValue("@SubCategory", column);

        con.Open();
        command.ExecuteNonQuery();
    }

    return true;
}

I am getting this error:

The value NULL can not be inserted into the SubCategoryID column, Test.dbo.Match_Subcategory_BusinessSector5 table. The column does not allow nulls.

Chnage

'@SubCategory'

to

@SubCategory

And

'@BusinessSector5'

to

@BusinessSector5

When using parameterized query you don't need to add anything arround the parameter name, it is not combined in your code, but being sent to the server separately (it sends the sql as you wrote it and a list of parameters). Because of that, you are protected againts sql injections and related problems.

"(Select [SubCategory].ID from SubCategory where Kategorie = @SubCategory)," +
"(SELECT [BusinessSector5].ID FROM BusinessSector5 where Description_DE = @BusinessSector5));",con))

remove quotes from your query

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM