我已经得到了一些代码:完全C#的附加信息:连接必须是有效的,并打开
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
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 MySql.Data.MySqlClient;
namespace mysql
{
/// <summary>
/// Interaction logic for LoginPage.xaml
/// </summary>
public partial class LoginPage : Page
{
private string conn;
private MySqlConnection connect;
AdminPage ap = new AdminPage();
public LoginPage()
{
InitializeComponent();
}
private void db_connection()
{
try
{
conn = "Server=localhost;Database=student;Uid=root;Pwd=admin;";
connect = new MySqlConnection(conn);
connect.Open();
}
catch (MySqlException e)
{
throw;
}
}
private bool validate_login(string user, string pass)
{
db_connection();
MySqlCommand cmd = new MySqlCommand();
cmd.CommandText = "Select * from student.admins where [email protected] and [email protected]";
cmd.Parameters.AddWithValue("@user", user);
cmd.Parameters.AddWithValue("@pass", pass);
cmd.Connection = connect;
MySqlDataReader login = cmd.ExecuteReader();
if (login.Read())
{
connect.Close();
return true;
}
else
{
connect.Close();
return false;
}
}
private void btn_login_Click(object sender, RoutedEventArgs e)
{
string user = txt_admin_name.Text;
string pass = txt_admin_passwd.Password;
if (user == "" || pass == "")
{
//MessageBox.Show("Empty Fields Detected ! Please fill up all the fields");
txt_errormessage.Text = "Empty Fields Detected! Please fill up all the fields!";
return;
}
bool r = validate_login(user, pass);
if (r)
{
//MessageBox.Show("Correct Login Credentials.\n You will be taken the Admin Page!");
this.NavigationService.Navigate(ap);
}
else
//MessageBox.Show("Incorrect Login Credentials");
txt_errormessage.Text = "Incorrect Login Credentials!";
}
}
}
,所以我需要一些错误处理:检查服务器的连接,并检查数据库的存在。我想写MessageBox。
我试过但是... “附加信息:连接必须有效且打开。”
在此先感谢!
我假设你已经声明conn并连接到其他地方我们看不到,因为我没有看到他们的任何声明。 –