连接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.”
标签:command1,string,C#,mysql,columnName,reader,连接 From: https://www.cnblogs.com/yu-beng/p/17611024.html