Proper way of getting a data from an Access Database

前端 未结 4 1531
挽巷
挽巷 2020-12-09 20:15

I\'m a bit confused of how to get a data from an access database. Is it proper to gather it first in a List then get those data from your List OR it is okay to just directly

4条回答
  •  春和景丽
    2020-12-09 21:03

    One thing that is sticking out like a sore thumb is the SQLInjection and to use Parameterised queries, eg:

    OleDbCommand command = new OleDbCommand("SELECT * from  Users WHERE LastName='@1'", connection);
    
    command.Parameters.AddWithValue("@1", textBox8.Text)
    

    What your doing is perfectly acceptable, although you would generally be better off to use a SQL Database.

    Edit: Here is how you seperate your business logic from the GUI:

    Class BusLogic
    {
     public List ListboxItems = new List();
     public void PopulateListBoxItems(string userName)
     {
      string connString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\redgabanan\Desktop\Gabanan_Red_dbaseCon\Red_Database.accdb";
      using (OleDbConnection connection = new OleDbConnection(connString))
      {
            connection.Open();
            OleDbDataReader reader = null;
            OleDbCommand command = new OleDbCommand("SELECT * from  Users WHERE LastName='@1'", connection);            
            command.Parameters.AddWithValue("@1", userName)
            reader = command.ExecuteReader();    
            while (reader.Read())
            {
                ListboxItems.Add(reader[1].ToString()+","+reader[2].ToString());
            }    
       }
     }    
    }
    

    GUI

    private void button3_Click(object sender, EventArgs e)
    {        
          var busLogic = new BusLogic();
          busLogic.PopulateListBoxItems(textBox8.Text);          
          \\listBox1.Items.Clear();
          ListboxItems.DataSource = busLogic.ListboxItems;
    }
    

提交回复
热议问题