gpt4 book ai didi

c# - 从 Access 数据库获取数据的正确方法

转载 作者:可可西里 更新时间:2023-11-01 08:54:47 25 4
gpt4 key购买 nike

我对如何从访问数据库中获取数据感到有点困惑。首先将它收集在一个列表中然后从您的列表中获取这些数据是否合适,或者直接在您的数据库中获取它是否合适?

我的代码工作得很好,但我想知道是否有更好的方法来做到这一点?? :

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

*我直接从数据库中获取记录,然后将其显示在列表框中。

最佳答案

像拇指一样突出的一件事是 SQLInjection 和使用参数化查询,例如:

OleDbCommand command = new OleDbCommand("SELECT * from  Users WHERE LastName='@1'", connection);

command.Parameters.AddWithValue("@1", textBox8.Text)

您所做的是完全可以接受的,尽管您通常最好使用 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());
}
}
}
}

界面

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

这种“MVC”方法的美妙之处在于,如果我们依赖于使用 Binding 绑定(bind)的控件,我们只真正需要测试 BusLogic。

ps 理想情况下,ListboxItems 应该是一个 IEnumerable 而不是 List,这样我们就不会向调用者公开任何添加/删除等功能。这是很好的 API 设计。

关于c# - 从 Access 数据库获取数据的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15148588/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com