首先C#使用MySQL数据库时,需要先添加配置引用文件(mysql.data.dll、mysql.data.entity.dll、mysql.visualstido.dll、mysql.web.dll)。添加完成之后,直接在程序中添加引用即可。
using MySql.Data.MySqlClient;
登录界面:
登录按钮按下代码:
private void button1_Click(object sender, EventArgs e)
{
try
{
if (textBox1.Text == "")
{
MessageBox.Show("用户名不能为空");
}
else
{
if (textBox2.Text == "")
{
MessageBox.Show("密码不能为空!");
}
else
{
admin_id = textBox1.Text;//获取账号
string admin_psw = textBox2.Text;//获取密码
string conn = "";
conn = "server=182.254.234.37;user id=cccyyy;password=cyg951026; database =bridge";//连接字符串,需要改成你自己的
MySqlConnection connection = new MySqlConnection(conn);//创建连接
connection.Open();//打开连接
string sql = string.Format("select count(*) from login where user_name='{0}' and password='{1}'", admin_id, admin_psw);//查询是否有该条记录,根据账户密码
MySqlCommand command = new MySqlCommand(sql, connection);//sqlcommand表示要向向数据库执行sql语句或存储过程
int i = Convert.ToInt32(command.ExecuteScalar());//执行后返回记录行数
if (i > 0)//如果大于1,说明记录存在,登录成功
{
command = new MySqlCommand("select * from login where user_name='" + admin_id + "'", connection);
MySqlDataReader sdr = command.ExecuteReader();
sdr.Read();
user = sdr["nick_name"].ToString().Trim();
Form main = new MainPage();
this.Hide();
main.Show();
}
else
{
MessageBox.Show("用户名或者密码错误!");
}
connection.Close();
}
}
}
catch (Exception ex)
{
MessageBox.Show("异常错误" + ex);
}
}
conn = "server=******;user id=cccyyy;password=cyg951026; database =bridge";
这是连接数据库的MySQL语句。服务可以是远程服务器的IP地址,或者本地,localhost、127.0.0.1或.表示。