来自C#的SQL查询

Csh*_*ner 4 c# sql

我试图从C#查询SQL Server数据库

我有课

Class_A 
{
  public fetch((string name, string last_name))
  {
    SqlConnection conn = null;
    double val = 0;
    string server = "123.444.22.sss";
    string dbase = "xyz";
    string userid = "cnsk";
    string password = "xxxxxx";
    string connection = "Data Source=" + server + ";Initial Catalog=" + dbase 
                        + ";User ID=" + userid + ";Password=" + password;

    conn = new SqlConnection(connection);

    try
    {
      conn.Open();
    }
    catch(Exception)
    {
      string e = "Database error contact administrator";
      MessageBox.Show(e, "Error!");
    }
    try
    {
      SqlDataReader myReader = null;
      SqlCommand myCommand = new SqlCommand("select * from table where NAME"
         + " = name and LAST_NAME = last_name", conn);
      myReader = myCommand.ExecuteReader();
      while (myReader.Read())
      {
        //do something

      }
    }
    catch (Exception e)
    {
      Console.WriteLine(e.ToString());
    }
    return (0);
  }
}
Run Code Online (Sandbox Code Playgroud)

我的查询中存在问题.

当我给出正常查询"select*from table"---这给了我完美的结果.

但是当我试图给出条件时它会给我错误.任何建议,解决这个问题?谢谢.

Ton*_*son 8

使用参数化查询和更多使用,并使用通用异常停止.

像这样的东西,其中somName和SomeLastName是你要查询的值.

String sql = "Select * From SomeTable Where [Name] = @Name and [Last_Name] = @LastName";
try
{
  using(SqlConnection conn = new SqlConnection(connection))
  {
    conn.Open();
    using( SqlCommand command = new SqlCommand(sql,conn))
    {
      command.Parameters.Add(new SqlParameter("Name", DbType.String,someName));
      command.Parameters.Add(new SqlParameter("LastName", DbType.String,someLastName));
      using(IDataReader myReader = command.ExecuteReader())
      {
        while (myReader.Read())
        {
           //do something
        }
      }
    }
  } 
  return 0; // Huh?
}
catch(SqlException sex)
{
   Console.Writeline(String.Format("Error - {0}\r\n{1}",sex.Message, sex.StackTace))
}
Run Code Online (Sandbox Code Playgroud)

不检查NB可能是一个愚蠢的


Rob*_*bie 6

尝试在where子句中围绕值添加引号,如下所示:

select * from table where NAME = 'name' and LAST_NAME = 'last_name'
Run Code Online (Sandbox Code Playgroud)

在使用变量的情况下,需要添加引号,然后将变量的值连接到字符串中.或者您可以String.Format像这样使用:

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