我对如何从访问数据库获取数据感到困惑.在List中首先收集它然后从列表中获取这些数据是否合适?或者可以直接在数据库中获取它?
我的代码工作得很好,但我想知道是否有更好的方法来做到这一点?:
private void button3_Click(object sender, EventArgs e)
{
OleDbConnection connection = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\redgabanan\Desktop\Gabanan_Red_dbaseCon\Red_Database.accdb");
connection.Open();
OleDbDataReader reader = null;
OleDbCommand command = new OleDbCommand("SELECT * from Users WHERE LastName='"+textBox8.Text+"'", connection);
reader = command.ExecuteReader();
listBox1.Items.Clear();
while (reader.Read())
{
listBox1.Items.Add(reader[1].ToString()+","+reader[2].ToString());
}
connection.Close();
Run Code Online (Sandbox Code Playgroud)
*我直接从数据库中获取记录,然后将其显示在列表框中.
Jer*_*son 18
像拇指一样伸出的一件事是SQLInjection并使用Parameterised查询,例如:
OleDbCommand command = new OleDbCommand("SELECT * from Users WHERE LastName='@1'", connection);
command.Parameters.AddWithValue("@1", textBox8.Text)
Run Code Online (Sandbox Code Playgroud)
你做的事情是完全可以接受的,尽管你通常最好使用SQL数据库.
编辑:以下是如何从GUI分离业务逻辑:
Class BusLogic
{
public List<string> ListboxItems = new List<string>();
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());
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
GUI
private void button3_Click(object sender, EventArgs e)
{
var busLogic = new BusLogic();
busLogic.PopulateListBoxItems(textBox8.Text);
\\listBox1.Items.Clear();
ListboxItems.DataSource = busLogic.ListboxItems;
}
Run Code Online (Sandbox Code Playgroud)