前言
使用Mysql数据库存取用户数据,实例参考:WPF实例系列一:登录、注册界面设计;对比参考WPF基础系列八:C# 导入/读取excel数据
一、构建mysql存取数据类
引入NuGet程序集MySql.Data,构建Mysql_Code类,实现mysql数据库的存取数据
using System;
using System.Collections;
using System.Data;
using System.Windows;
//引入MySQL
using MySql.Data.MySqlClient;
namespace sample5
{
public class Mysql_Code
{
static string constring = "server = 'localhost'; uid = 'root'; pwd = 'djz19960824'; database = 'test';"; //定义连接mysql字符串
MySqlConnection sqlCnn = new MySqlConnection(constring); //连接mysql
#region 读取Mysql数据库信息
public Hashtable Mysql_read()
{
string username;
string password;
string cmdstring = "select * from code"; //写入sql
MySqlCommand sqlCmd = new MySqlCommand(cmdstring, sqlCnn); //创建命令对象
Hashtable h = new Hashtable();
try
{
sqlCnn.Open(); //打开数据库
MySqlDataReader rec = sqlCmd.ExecuteReader();
while (rec.Read())
{
username = rec.GetString(0);
password = rec.GetString(1);
h.Add(username, password);
}
return h;</