打开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