C# - [ 数据库 ] 连接MySql

C#连接MySql



<一> 双向配置

1> MySql安装connector/Net(MySql安装可选项)

官网下载:https://dev.mysql.com/downloads/connector/net

2> 安装MySql.Net类库(VS):


<二> 基本操作

using System;
using MySql.Data.MySqlClient;

namespace MySQL_01
{
    class Program
    {
        static Print.Print print = Console.Write;
        static Print.Print println = Console.WriteLine;
        static void Main(string[] args)
        {
            var conn_str = @"user=root;
                             pwd=123456;
                             server =localhost;
                             database =day1015;";
            var conn = new MySqlConnection(conn_str);
            try
            {
                conn.Open();
                print("数据库 [day1015] 连接成功!");

                //获取行数与列数
                var command = new MySqlCommand("select count(*) from aaa", conn);
                var reader = command.ExecuteReader();
                var columns_number = reader.FieldCount;
                var rows_number = 0;
                if (reader.Read())
                {
                    rows_number = Convert.ToUInt16(reader[0]);
                }
                println($"{ rows_number }行");
                println($"{ columns_number }列");
                reader.Close();

                //输出数据库中所有数据
                command = new MySqlCommand("select * from aaa", conn);
                reader = command.ExecuteReader();
                if (reader.HasRows)
                {
                    while (reader.Read())
                    {
                        for(int i = 0; i < columns_number; i++)
                        {
                            print(reader[0]+" ");
                        }
                        println("");
                    }
                }
                else
                {
                    print("数据库为空!");
                }
                reader.Close();

            }
            catch(Exception e){
                println(e.Message);
            }
            finally
            {
                conn.Close();
            }
        }
    }
}

发布了544 篇原创文章 · 获赞 512 · 访问量 71万+
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 数字20 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览