C#连接Mysql练习

1.下载mysql-connector-net-8.0.12并安装,在引用里添加Mysql.Data。

2.using MySql.Data.MySqlClient;这句话要写上。如图所示

3.   创建连接字符串,其中如果不写        SslMode = none     这句话会报错

       “MySql.Data.MySqlClient.MySqlException”类型的未经处理的异常在 MySql.Data.dll 中发生 ,

        其他信息: The host localhost does not support SSL connections.

 string str = "Server=localhost;User Id=root;Password=hermione9;Database=demo;SslMode = none;";
 MySqlConnection con = new MySqlConnection(str);//实例化链接 

附上我写的练习注册小程序,实现信息录入Mysql数据库

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using MySql.Data.MySqlClient;

namespace WindowsFormsApplication2
{
    public partial class Form1 : Form
  
    {
        public Form1()
        {
            InitializeComponent();
           
        }
        public void c()
        {
            txtId.Text = "";
            txtPassword.Text = "";
            txtName.Text = "";
            txtMail.Text = "";
        }
        private void label1_Click(object sender, EventArgs e)
        {

        }

        private void Form1_Load(object sender, EventArgs e)
        {
            
        
        }

        private void btn1_Click(object sender, EventArgs e)
        {
            //输入不能为空
            if (txtId.Text == "" | txtPassword.Text == "" | txtName.Text == "" | txtMail.Text == "")
            {
                MessageBox.Show("请输入完整信息");
                return;
            }
            ///LoginId不能为重复
            //定义链接字符串
            string connString = "Server=localhost;DataBase=demo;Uid=root;Pwd=hermione9;SslMode = none";
            //创建连接对象
            MySqlConnection conn = new MySqlConnection(connString);
            //组合sql查询语句
            string sqlSelect = "select id from demo where id='" + txtId.Text.Trim() + "'";
            MySqlCommand cmd1 = new MySqlCommand(sqlSelect, conn);
            //执行查询
            conn.Open();
            object result1 = cmd1.ExecuteScalar();
            //判断账号是否重复
            if (result1 != null)
            {
                MessageBox.Show("该账户已被注册");
                return;
            }
            conn.Close();


            string str = "Server=localhost;User Id=root;Password=hermione9;Database=demo;SslMode = none;";
            MySqlConnection con = new MySqlConnection(str);//实例化链接       
            string sql = "insert into demo(id,password,name,mail)";
            sql += "values('{0}','{1}','{2}','{3}')";
            sql = string.Format(sql, txtId.Text, txtPassword.Text,txtName.Text, txtMail.Text);
            MySqlCommand cmd = new MySqlCommand(sql, con);
            con.Open();
            int reslt = cmd.ExecuteNonQuery();
            c();
            MessageBox.Show("注册成功");
            con.Close();
            

        }
    }
}

注:

猜你喜欢

转载自blog.csdn.net/Qhj_Miracle/article/details/81358128