c#连接mysql总是报错实例名称错误

程序报错如图,用navicate操作数据库没问题,但c#连接数据库不行。用的是默认实例。安装也装了odbc。

img

img

img

一、Unable to connect to any of the specified MySQL hosts?
读取数据库地址错误产生的超时报警。更新输入地址,本地localhost或者127...**为任意值)

二、Authentication to host ‘127.0.0.1’ for user ‘root’ using method ‘caching_sha2_password’ failed with message: Unknown database ‘******’”
连接数据库名称错误

三、Authentication to host ‘127.0.0.1’ for user ‘root’ using method ‘caching_sha2_password’ failed with message: Access denied for user ‘root’@‘localhost’ (using password: YES)”
连接数据库密码错误,密码为登录密码

四、无法运行添加环境变量(与安装的过程有关,如果没有成功需要添加)

已经添加完,上一条bin 就是。

五、具体程序及界面

程序放在button.click触发

        //文件明细
        string server = "127.0.0.1";
        string database = "inspection";
        string mypwd = "Mahle1234";
        string M_str_sqlcon = "server=" + server + ";username=root;password=" + mypwd + ";database=" + database;
        //string M_str_sqlcon = "server = localhost; port = 3306;user = root; password =Mahle1234 ;database =inspection";
        textBox1.Text  = M_str_sqlcon;


        //将链接MySql所有参数实例化
        MySqlConnection My_con = new MySqlConnection(M_str_sqlcon);                      //打开数据库
        //链接数据库打开
        My_con.Open();
        //生成字符串变量
        string sqlstr = "SELECT * FROM inspection.inspectioncase;";
        //实例化数据适配器(检索和保存数据)可以本地操作,然后整体传到数据库
        MySqlDataAdapter SQLda = new MySqlDataAdapter(sqlstr, My_con);
        //参数设置
        DataSet My_Dataset = new DataSet();
        //把MySql中内容填充到table中
        SQLda.Fill(My_Dataset, "table");
        //实例化dt
        DataTable dt = new DataTable();
        dt = My_Dataset.Tables["table"];
        //textBox3.Text = dt.Columns[2].ToString();
        textBox3.Text = "";
        //把dt放到dataGridView中
        dataGridView1.DataSource = dt;
        My_con.Close();

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
总结
安装mysql后运行有时候会出现运行错误,可能是环境变量没有添加成功,需要手动添加然后正常。安装成功后删除环境变量也可以用c#调取mysql。此程序只是查看数据库内容增加.Add();删除Delete();