c# - 添加列表在 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。目前我不创建类,但如果你需要告诉我,我需要创建。
解决方案
您需要创建一个 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());
推荐阅读
- java - BufferedReader 如何与 Socket 交互?关于 Socket 的工作原理
- html - CSS:倾斜居中的背景
- excel - VBA 代码从文本变为范围的数值,但列不高?
- scala - 如何使用无形为具有依赖类型的类型类创建实例
- android - Android - AlarmManager 不触发 BroadcastReceiver 以显示本地通知
- c# - Dialogflow 和 C# 的音频响应
- reactjs - 如何渲染反应组件onClick?
- django - 在模板中向 django listview 对象添加详细信息
- mysql - 如何在同一 MySQL 服务器上的两 (2) 个不同数据库中创建存储过程
- python - Dataframe.sample 方法不返回正确的索引