从C#SQL查询 [英] SQL query from C#

查看:142
本文介绍了从C#SQL查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从C#查询SQL Server数据库

I am trying to query SQL Server database from C#

我有类

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

有是我的查询中的一个问题。

There is a problem in my query.

当我给普通查询SELECT * FROM表---这给了我完美的效果。

When I give normal query "select * from table" --- this gives me perfect results.

但是,当我试图给那里的条件它给我的错误。任何建议,解决这一问题?
谢谢

But when I try to give where condition it gives me error. Any suggestions, to fix this? Thanks.

推荐答案

尝试像这样在where子句中添加周围的值引号:

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

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

在你的情况,你使用的是你需要的变量的值加引号,然后连接成的字符串变量。或者你可以使用的String.Format 是这样的:

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);

这篇关于从C#SQL查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆