C#连接mysql

 下载连接的库

https://files.cnblogs.com/files/blogs/741126/mysql-connector-net-6.10.9-src.zip?t=1691381333&download=true

我的.net框架  4.7.1 (本来使用的是4.0,但是不符合引用库的框架标准,后面备份了一下转为4.7.1,记住是所有的项目都要改为统一的框架,目前没发现任何改变框架后的影像)

 

连接mysql

//使用web.config配置 ConnectionString 连接数据库
//<add key="ConnectionString" value="server=localhost;port=33**;database=***;user id=**;password=***;Charset=utf8;"/>
string connectionString = ConfigurationManager.AppSettings["ConnectionString"];
//
MySqlConnection 是连接mysql的, SqlConnection 是连接sqlserver的,注意区别
using (MySqlConnection connection = new MySqlConnection(connectionString))

{

                    connection.Open();
                    string query = "SELECT * FROM 表名";
                    MySqlCommand command1 = new MySqlCommand(query, connection);
                    MySqlDataReader reader = command1.ExecuteReader();
                    // 获取表的模式信息
                    DataTable schemaTable = reader.GetSchemaTable();

                    while (reader.Read())
                    {
                        // 遍历模式信息并输出字段名
                        foreach (DataRow row in schemaTable.Rows)
                        {
                            string columnName = row["ColumnName"].ToString();
                            string columnValue = reader[columnName].ToString();
                           // Console.WriteLine(columnName);
                            Console.WriteLine($"{columnName}: {columnValue}");
                        }
                    }
                    reader.Close();
                    command1.Dispose();
                }

 

 

BUG1 :

MySql.Data.MySqlClient.MySqlException:“Unable to connect to any of the specified MySQL hosts.”

 这里需要加入自己的端口port:****

<add key="ConnectionString" value="server=localhost;port=33**;database=***;user id=root;password=***;Charset=utf8;"/>

 

 

BUG2 :

MySql.Data.MySqlClient.MySqlException:“Invalid attempt to Read when reader is closed.”

 

posted @ 2023-08-07 11:36  雨崩  阅读(146)  评论(0编辑  收藏  举报