c# - 来自 C# 的 SQL 查询

标签 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);
  }
}

我的查询有问题。

当我给出普通查询“select * from table”时——这给了我完美的结果。

但是当我尝试给出 where 条件时,它给了我错误。有什么建议可以解决这个问题吗? 谢谢。

最佳答案

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

像这样,其中 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))
}

NB not checked 可能有点傻

关于c# - 来自 C# 的 SQL 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9966301/

相关文章:

c# - Windows Phone 应用程序中 Dispatcher.BeginInvoke 方法的用途是什么

c# - MVC3 HandleError 不显示错误页面

sql - 在SQL SERVER中使用Long和Lat计算点之间的距离

php - 我希望我的子查询返回多个值(= 为每个成员),这可能吗?

c# - 向 SQL Server 发送空参数

c# - 在 LINQ-C# 中不同

c# - 如何从我的 Hololens 中编辑 Streamingassets 中的 XML 文件

java - while (rs.next()) 没有返回所有结果?

c# - Android布局问题..不知道如何调试

mysql - 即使 id 为空,我们如何显示记录?