版本和库:
- 目标框架:NET 8.0
- 需要的库:MySql.Data 9.0.0
演示:
Xaml:
<Window x:Class="Csharp_Mysql_Login.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:Csharp_Mysql_Login"
mc:Ignorable="d"
Title="Login" Height="400" Width="400">
<Grid Width="400" Margin="0,0,0,1">
<StackPanel Orientation="Vertical" Margin="100">
<TextBlock Text="Username:"/>
<TextBox x:Name="txtUsername" Margin="5"/>
<TextBlock Text="Password:"/>
<PasswordBox x:Name="txtPassword" Margin="5"/>
<Button x:Name="btnLogin" Content="Login" Click="btnLogin_Click" Margin="5"/>
<TextBlock x:Name="lblMessage" Foreground="Red"/>
</StackPanel>
</Grid>
</Window>
CS:
using MySql.Data.MySqlClient;
using System.Windows;
namespace Csharp_Mysql_Login
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void btnLogin_Click(object sender, RoutedEventArgs e)
{
string username = txtUsername.Text;
string password = txtPassword.Password;
try
{
string connectionString = "server=IP地址;userid=用户名;password=密码;database=数据库名";
using (MySqlConnection connection = new MySqlConnection(connectionString))
{
connection.Open();
string query = "SELECT * FROM users WHERE username = @username AND password = @password";
using (MySqlCommand command = new MySqlCommand(query, connection))
{
command.Parameters.AddWithValue("@username", username);
command.Parameters.AddWithValue("@password", password);
using (MySqlDataReader reader = command.ExecuteReader())
{
if (reader.HasRows)
{
// 登录成功
lblMessage.Text = "登录成功!";
}
else
{
// 登录失败
lblMessage.Text = "用户名或密码无效.";
}
}
}
}
}
catch (Exception ex)
{
lblMessage.Text = "Error: " + ex.Message;
}
}
}
}
数据表:
CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(255) NOT NULL,
password VARCHAR(255) NOT NULL
) CHARACTER SET utf8mb4;
测试数据:
INSERT INTO users (username, password) VALUES ('admin', 'admin');
注意:
- C# 和数据表并没有写加密,而是明文数据;只要账号和密码正确就提示:“登录成功!”
- 代码要自己修改一下,才能实现加密
您当前的等级为
登录后免费下载登录
小黑屋反思中,不准下载!
评论后刷新页面下载评论
支付¥以后下载
请先登录
您今天的下载次数(次)用完了,请明天再来
支付积分以后下载立即支付
支付以后下载立即支付
您当前的用户组不允许下载升级会员
您已获得下载权限
您可以每天下载资源次,今日剩余次