C# MySQL链接入门

huangting 4月前 ⋅ 314 阅读

1,引用mysql 官网dll文件

MySQL.data.dll

2,引进命名空间

using MySql.Data.MySqlClient;

namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }
    

    private void button1_Click(object sender, EventArgs e)
    {
        string connstr = "data source=localhost;database=shuju;user id=root;password=root;pooling=false;charset=utf8";//链接字符
        MySqlConnection conn = new MySqlConnection(connstr);//获取链接
        try
        {
            string username = textBox1.Text;
            string password = textBox2.Text;
            
            conn.Open();//打开链接
            string sqlSelect = string.Format("select * from user where username='{0}' and password='{1}';", username, password);
            //sql

            MySqlCommand comd = new MySqlCommand(sqlSelect, conn);//获取资源

            MySqlDataReader rd = comd.ExecuteReader();//读取数据
            if (rd.Read())//读取下一条,如果有
            {
                //MessageBox.Show("ok");
                Form2 f2 = new Form2();//新窗体
                f2.Show();//显示新窗体
                this.Hide();//此窗体影藏
            }
            else
                MessageBox.Show("账号密码错误");
        }
        catch (Exception e1)
        {
            //系统排错
            MessageBox.Show(e1.ToString());
        }
        finally
        {
            conn.Close();//关闭链接
        }
       

    }
}

}

``


全部评论: 0

    我有话说: