我是 C# 编程的新手,并尝试使用 C# 和 MySQL 数据库在 WPF 中创建登录表单。当我运行我的 WPF 并尝试插入数据时,我在这一行遇到错误:
using (var cmd = new MySqlCommand("Select salt From niki where user_name = @username"))
{
cmd.Parameters.AddWithValue("@username", username);
salt = cmd.ExecuteScalar() as string;
}
错误是连接必须有效且打开。你知道问题出在哪里吗?
伙计们,这是我只是用虚幻替换敏感数据字段的整个代码,虽然我改变了东西,但我仍然得到错误。你能确定问题出在哪里吗?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using MySql.Data.MySqlClient;
using System.Security.Cryptography;
using System.Security.Authentication;
using System.Security.Permissions;
using System.Security.AccessControl;
using System.Security.Policy;
using System.Security.Principal;
using System.Security.Util;
namespace ECBSRecruitmentAgencySoftware
{
public partial class LogIn : Form
{
public LogIn()
{
InitializeComponent();
}
static byte[] GenerateSaltedHash(string plainText, string salt)
{
HashAlgorithm algorithm = new SHA256Managed();
byte[] plainTextBytes = System.Text.Encoding.Unicode.GetBytes(plainText);
byte[] saltBytes = Convert.FromBase64String(salt);
byte[] plainTextWithSaltBytes = new byte[plainTextBytes.Length + saltBytes.Length];
saltBytes.CopyTo(plainTextWithSaltBytes, 0);
plainTextBytes.CopyTo(plainTextWithSaltBytes, salt.Length);
byte[] hash = algorithm.ComputeHash(plainTextWithSaltBytes);
return hash;
}
public bool tryLogin(string username , string password)
{
using (var con = new MySqlConnection("host=tara.rdb.superhosting.bg;user=sozopouk;password=27051996;database=sozopouk_test2;"))
{
con.Open();
var salt = string.Empty;
using (var cmd = new MySqlCommand("Select salt From niki where user_name = @username"))
{
cmd.Parameters.AddWithValue("@username", username);
salt = cmd.ExecuteScalar() as string;
}
if (string.IsNullOrEmpty(salt)) return false;
var hashedPassword = GenerateSaltedHash(password, salt);
using (var cmd = new MySqlCommand("Select * FROM niki WHERE user_name = @username and user_password = @password"))
{
cmd.Parameters.AddWithValue("@username", username);
cmd.Parameters.AddWithValue("@password", hashedPassword);
using (var reader = cmd.ExecuteReader())
{
return reader.Read();
}
}
}
}
private void button1_Click(object sender, EventArgs e)
{
if (tryLogin(user.Text, pass.Text) == true)
{
MainScreen F2 = new MainScreen();
F2.Show();
this.Hide();
}
else MessageBox.Show("Wrong details!");
}
}
}
你的意思是我必须更新:
using (var con = new MySqlConnection("host=tara.rdb.superhosting.bg;user=sozopouk;password=27051996;database=sozopouk_test2;"))
{
con.Open();
var salt = string.Empty;
using (var cmd = new MySqlCommand("Select salt From niki where user_name = @username"))
{
cmd.Parameters.AddWithValue("@username", username);
salt = cmd.ExecuteScalar() as string;
}
enter code here
enter code here
使用您生成的代码?如果是,我实际上如何连接到我的 MySQL 数据库?