首页 > 解决方案 > 添加列表在 C# 中搜索子字符串

问题描述

我正在创建应用程序,但我有一个问题。

客户端在文本框中写入用户名,例如 3 个字母并在数据库(访问)中搜索并添加数据库。

示例:用户:Rui。并在数据库中搜索所有名称用户“Rui”。

//libraries
using Microsoft.VisualStudio.OLE.Interop;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.OleDb;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

private void textBox1_TextChanged(object sender, EventArgs e)
{
    OleDbConnection conexao = new OleDbConnection(string.Format(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source= {0}\Teste.accdb", Path.GetDirectoryName(Assembly.GetEntryAssembly().Location)));
        
    List<string> Users = new List<string>();

    
    OleDbCommand STK = new OleDbCommand($"SELECT NºCliente, NomeUser, CodigoPostal, NIF", conexao);
    STK.CommandText = $" SELECT* FROM MyTable WHERE Str(Lista_Pokemon) like '*{textBox1.Text}*'";

    User.Clear();
    //this code is invention, probably is wrong

    for(int d=0; d<Stk.Count()-1; d++)
         User.Add(...);
}

如果你能帮助我,谢谢。这个项目是c#,net framework,数据库是Access 2010。目前我不创建类,但如果你需要告诉我,我需要创建。

标签: c#listsearcholedb

解决方案


您需要创建一个 DbReader 并移动到下一行直到结束:

OleDbCommand STK = new OleDbCommand($"SELECT NºCliente, NomeUser, CodigoPostal, NIF", conexao);
STK.CommandText = $" SELECT * FROM MyTable WHERE Str(Lista_Pokemon) like '%{textBox1.Text}%'";

Users.Clear();

var reader = STK.ExecuteReader();
while (reader.Read())
    Users.Add(reader["Lista_Pokemon"].ToString());

就安全性而言,将用户输入线程化到查询文本中被认为是一种危险的做法,而且在逻辑上也不是不安全的。最好用参数“按书”行事:

OleDbCommand STK = new OleDbCommand();
STK.Connection = conexao;
STK.CommandText = "SELECT * FROM tblCliente WHERE User like @userParameter";
STK.Parameters.AddWithValue("@userParameter", $"%{textBox1.Text}%")

Users.Clear();

var reader = STK.ExecuteReader();
while (reader.Read())
    Users.Add(reader["User"].ToString());

推荐阅读