NetCore连接MySQL

打开VS,工具》NuGet包管理器》管理解决方案的NuGet程序包,搜索MySql.Data并安装

测试连接MySQL的代码:

using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using MySql.Data.MySqlClient;

namespace ZZTCore.Controllers
{
    public class LoginController : Controller
    {
        public IActionResult Index()
        {
            DataTable dt = new DataTable();
            DataSet ds = new DataSet();
            try
            {
                using (MySqlConnection con = new MySqlConnection("Data Source=localhost;User ID=root;Password=zt102545;Database=employees;Allow User Variables=True;Charset=utf8;"))
                {
                    if (con.State != ConnectionState.Open)
                        con.Open();
                    MySqlDataAdapter sda = new MySqlDataAdapter("select * from titles", con);
                    sda.Fill(ds);
                    con.Close();
                }
            }
            catch (Exception ex)
            {
                string s = ex.Message;
            }
            return View();
        }
    }
}

文章目录 Mysql报错问题汇总

 

1 远程报错问题

报错问题:Host ‘XXX’ is not allowed to connect to this MySQL server

1.1 防火墙允许3306端口

首先控制面板——防火墙——高级设置 ——入站规则——右键新建规则——允许3306端口(MySQL的默认端口)

1.2 修改环境变量(用于cmd可以运行mysql指令)

在这里插入图片描述

1.3 执行cmd命令

在安装Mysql数据库的主机上登录root用户:

执行mysql -u root -p 再输入密码
在这里插入图片描述
执行SQL语句
在这里插入图片描述
修改host值,改为%,便可以远程访问了
在这里插入图片描述
最后执行flush privilegs使配置立即生效

2连接报错问题

报错问题:Client does not support authentication protocol requested by server; consider upgrading MySQL client

2.1解决方法

用CMD连接到mysql执行以下sql

//修改加密方式。'123456'是自己的密码
alter user 'root'@'localhost' identified with mysql_native_password by '123456';
//刷新立即生效
flush privileges;

3.启动mysql报错问题

报错问题:

[root@localhost ~]# mysql -uroot -p123456
mysql: [Warning] Using a password on the command line interface can be insecure.
ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' (2)

出现这个报错是因为mysql服务没有启动。执行以下指令启动mysql服务

service mysqld start

如果启动失败可以查看mysql日志(LINUX环境下):

less /var/log/mysqld.log
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值