usingSystem;usingSystem.Collections.Generic;usingSystem.ComponentModel;usingSystem.Data;usingSystem.Drawing;usingSystem.Linq;usingSystem.Text;usingSystem.Threading.Tasks;usingSystem.Windows.Forms;usingMySql.Data.MySqlClient;namespaceMySQLTest
{public partial classForm1 : Form
{
Form2 formMain= newForm2();
MySqlConnection m_Conn= newMySqlConnection();publicForm1()
{
InitializeComponent();
}private void Form1_Load(objectsender, EventArgs e)
{
m_Conn.ConnectionString= "Server=localhost;Port=3306;Database=test; User=root;Password=root;";
}private void button1_Click(objectsender, EventArgs e)
{try{string sql = "";using (MySqlCommand cmd = newMySqlCommand())
{if (m_Conn.State !=ConnectionState.Open)
{
m_Conn.Open();
}
sql= "select name,pass from userinfo where name=@NAME and pass=@PASSWD";
cmd.Parameters.AddWithValue("@NAME", textBox1.Text.Trim());
cmd.Parameters.AddWithValue("@PASSWD", textBox2.Text.Trim());
cmd.Connection=m_Conn;
cmd.CommandText=sql;
MySqlDataReader reader=cmd.ExecuteReader();if(reader.Read())
{if (reader["name"].ToString().CompareTo(textBox1.Text.Trim()) == 0 && reader["pass"].ToString().CompareTo(textBox2.Text.Trim()) == 0)
{this.Hide();
formMain.ShowDialog();this.Show();
}
}else{
MessageBox.Show("帐号或密码错误,请检查!", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
reader.Close();
}
}catch(Exception)
{throw;
}
}private void button2_Click(objectsender, EventArgs e)
{this.Close();
}private void Form1_FormClosed(objectsender, FormClosedEventArgs e)
{try{if (m_Conn.State !=ConnectionState.Closed)
{
m_Conn.Close();
}
}catch(Exception)
{throw;
}
}private void textBox2_KeyPress(objectsender, KeyPressEventArgs e)
{if (e.KeyChar == 13)
{
button1_Click(sender, e);
}
}
}
}