HAG_BIB_Projekt/PrototypWPFHAG/MainWindow.xaml.cs

108 lines
3.3 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using System.Data;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using MahApps.Metro.Controls;
using Npgsql;
using Npgsql.Replication;
namespace PrototypWPFHAG;
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : MetroWindow
{
public MainWindow()
{
InitializeComponent();
// TestConnection();
// Console.ReadKey();
}
private void loginButton_Click(object sender, RoutedEventArgs e)
{
// 从用户输入中获取用户名和密码
string username = UsernameTextBox.Text; // 获取用户名
string password = PasswordTextBox.Password; // 获取密码
// 调用 ValidateUser 方法验证用户凭据
if (ValidateUser(username, password))
{
MessageBox.Show("ok", "Login Successful", MessageBoxButton.OK, MessageBoxImage.Error);
}
else
{
// 如果验证失败,显示错误信息
MessageBox.Show("Invalid username or password.", "Login Failed", MessageBoxButton.OK, MessageBoxImage.Error);
}
}
private bool ValidateUser(string username, string password)
{
// 获取数据库连接
using (var con = GetConnection())
{
con.Open(); // 打开数据库连接
string query = "SELECT COUNT(*) FROM USER WHERE UserName = @username AND Password = @password;";
using (var cmd = new NpgsqlCommand(query, con))
{
// 使用参数化查询防止 SQL 注入
cmd.Parameters.AddWithValue("@username", username);
cmd.Parameters.AddWithValue("@password", password);
// 执行查询并获取结果
int count = (int)cmd.ExecuteScalar();
return count > 0; // 如果匹配记录数量大于 0返回 true
}
}
}
private static void TestConnection()
{
using (NpgsqlConnection con = GetConnection())
{
con.Open();
if (con.State == ConnectionState.Open)
{
Console.WriteLine("Connected to Server");
}
}
}
private static NpgsqlConnection GetConnection()
{
return new NpgsqlConnection(@"Server=localhost;Port=5432;User Id=postgres;Password=postgres;Database=postgres;");
}
//class Program
//{
// static void Main(string[] args)
// {
// TestConnection();
// Console.ReadKey();
// }
// private static void TestConnection()
// {
// using(NpgsqlConnection con = GetConnection()){
// con.Open();
// if (con.State == ConnectionState.Open) {
// Console.WriteLine("Connected to Server");
// }
// }
// }
// private static NpgsqlConnection GetConnection()
// {
// return new NpgsqlConnection(@"Server=localhost;Port=5432;User Id=postgres;Password=postgres;Database=TestServer;");
// }
//}
}