我已經得到了一些代碼:完全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並連接到其他地方我們看不到,因爲我沒有看到他們的任何聲明。 –