SQL query from C#

前端 未结 4 1213
感情败类
感情败类 2020-12-20 23:32

I am trying to query SQL Server database from C#

I have class

Class_A 
{
  public fetch((string name, string last_name))
  {
    SqlConnection conn          


        
4条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-20 23:39

    ⚠️ WARNING This answer contains a SQL injection security vulnerability. Do not use it. Consider using a parameterized query instead, as described in some of the other answers to this question (e.g. Tony Hopkinson's answer).

    Try adding quotes around the values in the where clause like this:

    select * from table where NAME = 'name' and LAST_NAME = 'last_name'
    

    In your case where you are using variables you need to add the quotes and then concatenate the values of the variables into the string. Or you could use String.Format like this:

    var sql = String.Format("select * from table where [NAME] = '{0}' and LAST_NAME = '{1}'", name, last_name);
    SqlCommand myCommand = new SqlCommand(sql);
    

提交回复
热议问题