【问题标题】:How to retrieve data from a SQL Server database in C#?如何在 C# 中从 SQL Server 数据库中检索数据?
【发布时间】:2012-12-19 18:09:17
【问题描述】:

我有一个包含 3 列 firstnameLastnameage 的数据库表。在我的 C# Windows 应用程序中,我有 3 个名为 textbox1 的文本框...我使用以下代码连接到我的 SQL Server:

SqlConnection con = new SqlConnection("Data Source = .;
                                       Initial Catalog = domain;
                                       Integrated Security = True");
con.Open();
SqlCommand cmd = new SqlCommand("Select * from tablename", con);

我想从我的数据库中获取值;如果我在textbox1 中给出一个值,它必须匹配数据库中的值并将其他详细信息检索到相应的文本框。

我试过这个方法,但它不起作用:

cmd.CommandText = "select * from tablename where firstname = '" + textBox1.Text + "' ";

如何才能将所有其他值检索到文本框?

【问题讨论】:

  • 您有firstnameLastnameagedomainName 是什么?为什么count(*)
  • 你为什么在你的选择中做一个计数(*)?通常你不应该做这种命令文本连接,因为你会冒sql注入的风险......想想用户输入“';drop table tablename;--”
  • @HamletHakobyan 抱歉,我为了说服而更改了代码,因为我忘了更改该术语
  • @CSharper 我认为这是我从Here引用的简单方法
  • “我试过这个方法,但它不起作用”根本不是对您问题的有用描述。

标签: c# sql sql-server


【解决方案1】:
 public Person SomeMethod(string fName)
        {
            var con = ConfigurationManager.ConnectionStrings["Yourconnection"].ToString();

            Person matchingPerson = new Person();
            using (SqlConnection myConnection = new SqlConnection(con))
            {
                string oString = "Select * from Employees where FirstName=@fName";
                SqlCommand oCmd = new SqlCommand(oString, myConnection);
                oCmd.Parameters.AddWithValue("@Fname", fName);           
                myConnection.Open();
                using (SqlDataReader oReader = oCmd.ExecuteReader())
                {
                    while (oReader.Read())
                    {    
                        matchingPerson.firstName = oReader["FirstName"].ToString();
                        matchingPerson.lastName = oReader["LastName"].ToString();                       
                    }

                    myConnection.Close();
                }               
            }
            return matchingPerson;
        }

这里有几件事需要注意:我使用了参数化查询,这使您的代码更安全。使用 "where x = "+ Textbox.Text +"" 部分创建 select 语句的方式使您面临 SQL 注入。

我已将其更改为:

  "Select * from Employees where FirstName=@fName"
  oCmd.Parameters.AddWithValue("@fname", fName);  

那么这段代码要做的是:

对您的数据库执行一条 SQL 语句,查看是否有任何名字与您提供的名字相匹配。 如果是这种情况,该人将被存储在 Person 对象中(请参阅下面的类答案)。 如果没有匹配,则 Person 对象的属性将为 null

显然我不完全知道你在做什么,所以有几点需要注意:当有超过 1 个人的名字匹配时,只有最后一个会被保存并返回给你. 如果您希望能够存储这些数据,可以将它们添加到 List<Person>

Person 类使其更简洁:

 public class Person
    {
            public string firstName { get; set; }
            public string lastName { get; set; }
    }

现在调用方法:

Person x = SomeMethod("John");

然后您可以使用来自 Person 对象的值填充您的文本框,如下所示:

txtLastName.Text = x.LastName;

【讨论】:

  • 这是一个绝妙的答案!
  • 确实非常好的答案。 try catch 声明是唯一缺少的东西
  • AddWithValue("@Fname", fName); F 在查询中应该是小写/大写
  • Fname和fname的参数名称不应该相似吗? “请注意,SqlParameter 实例的 ParameterName 属性必须与 SqlCommand SQL 命令字符串中使用的参数完全一样”参考:csharp-station.com/Tutorial/AdoDotNet/Lesson06
  • 请注意 using 语句将处理 connection.close。在后台,SqlConnection.Dispose() 调用 SqlConnection.Close() 方法,而 SqlCommand.Dispose() 调用 SqlCommand.Close()。
【解决方案2】:

创建一个名为 DbManager 的类:

Class DbManager
{
 SqlConnection connection;
 SqlCommand command;

       public DbManager()
      {
        connection = new SqlConnection();
        connection.ConnectionString = @"Data Source=.     \SQLEXPRESS;AttachDbFilename=|DataDirectory|DatabaseName.mdf;Integrated Security=True;User Instance=True";
        command = new SqlCommand();
        command.Connection = connection;
        command.CommandType = CommandType.Text;
     } // constructor

 public bool GetUsersData(ref string lastname, ref string firstname, ref string age)
     {
        bool returnvalue = false;
        try
        {
            command.CommandText = "select * from TableName where firstname=@firstname and lastname=@lastname";
            command.Parameters.Add("firstname",SqlDbType.VarChar).Value = firstname;
 command.Parameters.Add("lastname",SqlDbType.VarChar).Value = lastname; 
            connection.Open();
            SqlDataReader reader= command.ExecuteReader();
            if (reader.HasRows)
            {
                while (reader.Read())
                {

                    lastname = reader.GetString(1);
                    firstname = reader.GetString(2);

                    age = reader.GetString(3);


                }
            }
            returnvalue = true;
        }
        catch
        { }
        finally
        {
            connection.Close();
        }
        return returnvalue;

    }

然后双击表单上的检索按钮(例如 btnretrieve)并插入以下代码:

 private void btnretrieve_Click(object sender, EventArgs e)
    {
        try
        {
            string lastname = null;
            string firstname = null;
            string age = null;

            DbManager db = new DbManager();

            bool status = db.GetUsersData(ref surname, ref firstname, ref age);
                if (status)
                {
                txtlastname.Text = surname;
                txtfirstname.Text = firstname;
                txtAge.Text = age;       
               }
          }
       catch
          {

          }
   }

【讨论】:

  • 可能会考虑在类上添加一个 IDisposable,然后使用 Using 进行自动清理。例如使用(DbManager db = new DbManager()) { ... }
【解决方案3】:

从数据库中检索数据:

private SqlConnection Conn;
 private void CreateConnection()
 {
    string ConnStr =
    ConfigurationManager.ConnectionStrings["ConnStr"].ConnectionString;
    Conn = new SqlConnection(ConnStr);
 }
 public DataTable getData()
 {
 CreateConnection();
    string SqlString = "SELECT * FROM TableName WHERE SomeID = @SomeID;";
    SqlDataAdapter sda = new SqlDataAdapter(SqlString, Conn);
    DataTable dt = new DataTable();
    try
    {
        Conn.Open();
        sda.Fill(dt);
    }
    catch (SqlException se)
    {
        DBErLog.DbServLog(se, se.ToString());
    }
    finally
    {
        Conn.Close();
    }
    return dt;
}

【讨论】:

    【解决方案4】:

    您可以在设置连接后使用这个简单的方法:

    private void getAgentInfo(string key)//"key" is your search paramter inside database
        {
            con.Open();
            string sqlquery = "SELECT * FROM TableName WHERE firstname = @fName";
    
            SqlCommand command = new SqlCommand(sqlquery, con); 
            SqlDataReader sReader;
    
            command.Parameters.Clear();
            command.Parameters.AddWithValue("@fName", key);
            sReader = command.ExecuteReader();
    
            while (sReader.Read())
            {
                textBoxLastName.Text = sReader["Lastname"].ToString(); //SqlDataReader
                //["LastName"] the name of your column you want to retrieve from DB
    
                textBoxAge.Text = sReader["age"].ToString();
                //["age"] another column you want to retrieve
            }
            con.Close();
        }
    

    现在您可以通过 textBoxFirstName 将密钥传递给此方法,例如:

    getAgentInfo(textBoxFirstName.Text);
    

    【讨论】:

      【解决方案5】:

      我们可以使用这种类型的 sn-p,我们通常使用这种代码来测试和验证 DB 到 API 字段的数据

      class Db
      {
          private readonly static string ConnectionString =
                  ConfigurationManager.ConnectionStrings
                              ["DbConnectionString"].ConnectionString;
          public static List<string> GetValuesFromDB(string LocationCode)
          {
              List<string> ValuesFromDB = new List<string>();
              string LocationqueryString = "select BELocationCode,CityLocation,CityLocationDescription,CountryCode,CountryDescription " +
                  $"from [CustomerLocations] where LocationCode='{LocationCode}';";
              using (SqlConnection Locationconnection =
                                       new SqlConnection(ConnectionString))
              {
                  SqlCommand command = new SqlCommand(LocationqueryString, Locationconnection);
                  try
                  {
                      Locationconnection.Open();
                      SqlDataReader Locationreader = command.ExecuteReader();
                      while (Locationreader.Read())
                      {
                          for (int i = 0; i <= Locationreader.FieldCount - 1; i++)
                          {
                              ValuesFromDB.Add(Locationreader[i].ToString());
                          }
                      }
                      Locationreader.Close();
                      return ValuesFromDB;
                  }
                  catch (Exception ex)
                  {
                      Console.WriteLine(ex.Message);
                      throw;
                  }
              }
      
          }
      
      }
      

      希望这可能会有所帮助

      注意:你们需要连接字符串(在我们的例子中 "DbConnectionString")

      【讨论】:

        【解决方案6】:
            DataTable formerSlidesData = new DataTable();
            DformerSlidesData = searchAndFilterService.SearchSlideById(ids[i]);
                        if (formerSlidesData.Rows.Count > 0)
                        {
                            DataRow rowa = formerSlidesData.Rows[0];
        
                            cabinet = Convert.ToInt32(rowa["cabinet"]);
                            box = Convert.ToInt32(rowa["box"]);
                            drawer = Convert.ToInt32(rowa["drawer"]);
                        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2012-10-11
          • 2020-07-25
          • 1970-01-01
          • 1970-01-01
          • 2016-03-17
          相关资源
          最近更新 更多