简体   繁体   中英

ASP.net c# simple query paramter question

        // Add into DB
        using (tblArtworkTemplatesTableAdapter tblAdapter = new tblArtworkTemplatesTableAdapter())
        {
            tblAdapter.Insert(DateTime.Now, "@specID");
            "@specID" = int.Parse(lstChooseSpec.SelectedValue)
        }

I know the code is wrong, just for illustration of my objective, how do I paramatise the input?

Generally it depends. If You are using any kind of ORM like LINQ to SQL or NHibernate, it will do it for You no questions asked. If YOu are doing it using Plain ADO objects (which I suppose is the case) then You will have to comeup with the Command (or SQLCommand or any other ICommand implementation) object and use SQLParameter class (or other parameter classes).

ICommand has the collection of parameters that You can arbitralily edit.

    SqlCommand cmd = new SqlCommand(
            "select * from STH where column = @SpecID", conn);

    //it might be useful to specify a type as well
    SqlParameter param  = new SqlParameter();
    param.ParameterName = "@SpecID";
    //I woudl use the TryParse method though
    param.Value         = int.Parse(lstChooseSpec.SelectedValue);

    cmd.Parameters.Add(param);

This line

"@specID" = int.Parse(lstChooseSpec.SelectedValue)

Is incorrect. You can't assign a value to a constant. You might mean something like

specId = int.Parse(lstChooseSpec.SelectedValue);

The rest of the code is confusing. Why are you parsing lstChooseSpec.SelectedValue to an integer, then trying to add it to the adapter as a DateTime? C# is strongly-typed: something is either an int or a DateTime , but cannot be both.

It might help if you could post the rest of the method.

Also, have a look at this overview on MSDN.

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