从C#中的数据库中检索数据

时间:2016-05-03 12:54:42

标签: c#

我是编程新手,现在正在使用C#,现在我正在尝试一些东西。我在ms访问中创建了一个包含行和列数据的数据库。我还创建了一个包含文本框的Windows窗体应用程序。我现在要做的是编写一个代码,从数据库表中的单个列和行中收集每个数据,并将其插入到Windows窗体中的每个文本框中。 这就是我所做的:

try 
{
    //...
    command.CommandText = "SELECT (Table1.matricule, Table1.name, Table1.department, Table1.specialty, Table1.session) FROM Table1 WHERE (((Table1.matricule)=[textBox6.Text]))";
    command.CommandType = CommandType.Text;
    connection.Open();

    OleDbDataReader reader = command.ExecuteReader();

    while (reader.Read())
    {
        Person p = new Person();

        textBox1.Text = reader["Table1.matricule"];
        textBox2.Text = reader["Table1.name"];
        textBox3.Text = reader["Table1.department"];
        textBox4.Text = reader["Table1.specialty"];
        textBox5.Text = reader["Table1.session"];

        personsList.Add(p);
    }
    return personsList;
}
catch (Exception)
{
    throw;
}

2 个答案:

答案 0 :(得分:1)

您需要在代码中实际设置参数值,而不是在字符串中指定它们:

// Parameterize the query
command.CommandText = "SELECT matricule, name, department, specialty, session FROM Table1 WHERE matricule = ?";

然后使用AddWithValue()方法在执行之前设置参数:

connection.Open();
// Set your parameter prior to executing the query
command.Parameters.AddWithValue("@matricule",textBox6.Text);
// Now execute your query
OleDbDataReader reader = command.ExecuteReader();

最后,您可能需要在Person个对象上填充属性,而不是设置文本框值(因为Person对象将为空):

 // Populate person properties within your loop
 Person p = new Person()
 {
      Matricule = reader["matricule"],
      Name = reader["name"],
      Department = reader["department"],
      Specialty = reader["specialty"],   
 }

考虑重构

您可以将这些更改与其他一些更改一起实施(包括使用using语句以确保正确关闭和处理对象):

// Define your list of people
var people = new List<Person>();
// Create your connection
using(var connection = new OleDbConnection("{your-connection-string}"))
{
     try 
     {
         // Define your query (and parameters)
         var query = "SELECT matricule, name, department, specialty, session FROM Table1 WHERE matricule = ?";
         // Define a using statement
         using(var command = new OleDbCommand(query, connection))
         {
             connection.Open();
             // Set your parameter prior to executing the query
             command.Parameters.AddWithValue("@matricule",textBox6.Text);
             // Execute your query
             using(var reader = command.ExecuteReader())
             {
                  // While you have rows, read them
                  while(reader.Read())
                  {
                       people.Add(new Person()
                       {
                           Matricule = reader["matricule"],
                           Name = reader["name"],
                           Department = reader["department"],
                           Specialty = reader["specialty"],   
                      });
                  }
                  // Return your collection
                  return people;
             }
         }
    }
    catch(Exception ex)
    {
         // Something blew up, handle accordingly
    }
}

答案 1 :(得分:0)

给定代码几乎没有问题:

1.使用参数化查询代替纯文本:

command.CommandText = "SELECT matricule, name, department, specialty, session FROM Table1 WHERE matricule = ?";
connection.Open();
command.Parameters.Add("@matricule",OleDbType.VarChar).Value= textBox6.Text;
OleDbDataReader reader = command.ExecuteReader();

2.我无法弄清楚你在这里使用personsList的原因: 如果预期的查询结果将包含多个行,则只会获得文本框中显示的最后一个值。如果它不是多行,则需要向person对象添加详细信息。

personsList.Add(new Person()
 {
      Matricule = reader["matricule"],
      Name = reader["name"],
      Department = reader["department"],
      Specialty = reader["specialty"],   
 });

3.每次访问reader对象的值时,都不需要使用Table1.。您只需使用以下方式阅读:

 textBox1.Text = reader["matricule"];
 // load rest of textboxes

4.整件事情如下:

command.Parameters.Add("@matricule",OleDbType.VarChar).Value= textBox6.Text;
connection.Open();
OleDbDataReader reader = command.ExecuteReader();
while (reader.Read())
{
   textBox1.Text = reader["matricule"];
   textBox2.Text = reader["name"];
   textBox3.Text = reader["department"];
   textBox4.Text = reader["specialty"];
   textBox5.Text = reader["session"];
   personsList.Add(new Person()
     {
          Matricule = reader["matricule"],
          Name = reader["name"],
          Department = reader["department"],
          Specialty = reader["specialty"],   
     });
}
相关问题