c#学习(一)--连接Mysql数据库的方式

一、纯代码连接

1、找到Mysql按照目录搜索MySql.Data.dll 找到MySql.Data.dll位置
在这里插入图片描述
2、添加MySql.Data.dl引用。
在这里插入图片描述
3、编写代码

using System.Data.SqlClient;
using MySql.Data.MySqlClient;

namespace _01AdoNetCourse
{
    class Program
    {
        static void Main(string[] args)
        {
            //SqlConnection connection = new SqlConnection();
            //string connStr = "server=.;database=newsdb;uid=root;pwd=123456";
            string sql_ip = "127.0.0.1";  //IP
            string sql_port = "3306"; //端口号
            string sql_user = "root";  //用户名  
            string sql_pw = "123456";  //密码
            string sql_name = "newsdb"; //数据库名
            string sql_con_state = "off";  //连接状态
            string connectionString = "server = " + sql_ip + "; userid = " + sql_user + "; password = " + sql_pw + "; database =" + sql_name + "; persistsecurityinfo = True;SslMode=None ;Charset=utf8;";
            MySqlConnection connection = new MySqlConnection(connectionString);
            connection.Open();
            Console.WriteLine("==================数据库连接成功==============================");//打印信息
            Console.ReadLine();
            connection.Close();
        }
    }
}

4、运行测试
在这里插入图片描述
5、成功
在这里插入图片描述
二、配置文件配置
1、同样引入MySql.Data.dll引用

2、添加System.Configuration引用
在这里插入图片描述3、配置App.config 数据库
在这里插入图片描述

<connectionStrings>
		<add name="conStri" connectionString="server=localhost;database=newsdb;uid=root;pwd=123456" providerName="MySql.Data.MySqlClient"/>
	</connectionStrings>

4、编写代码连接

 MySqlConnection connection = new MySqlConnection();

            string str = ConfigurationManager.ConnectionStrings["conStri"].ConnectionString;
            connection.ConnectionString = str;
             connection.Open();
            Console.WriteLine("连接成功");
            Console.ReadLine();
            connection.Close();

5、启动
在这里插入图片描述
6、成功
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

一叶飘零晋

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值