C#中连接MySql数据库,需要配置MySql.Data。
项目- 管理NuGet程序包 – 安装MySql.Data。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
using MySql.Data.MySqlClient; using System; namespace MySQL { class Program { static void Main(string[] args) { string server = "172.0.0.1"; string database = "test"; string uid = "root"; string password = "123456"; string SslMode = "none"; string connectionString; connectionString = "SERVER=" + server + ";" + "DATABASE=" + database + ";" + "UID=" + uid + ";" + "PASSWORD=" + password + ";" + "SslMode=" + SslMode; MySqlConnection mycon = new MySqlConnection(connectionString); mycon.Open(); MySqlCommand mycmd = new MySqlCommand("insert into buyer(name,password,email) values('小王','dikd3939','1134384387@qq.com')", mycon); if (mycmd.ExecuteNonQuery() > 0) { Console.WriteLine("数据插入成功!"); } Console.ReadLine(); mycon.Close(); } } } |
运行上述代码,如果出现异常 “IOException: Unable to read data from the transport connection: 由于连接方在一段时间后没有正确答复或连接的主机没有反应,连接尝试失败”。首先,确认数据库是否允许远程连接;其次,防火墙是否打开;最后,连接字符串是否正确,是否支持SSL。
出现异常“The host localhost does not support SSL connections.”说明不支持SSL,需要在连接字符串里添加SslMode = "none"。
from:https://blog.csdn.net/liyazhen2011/article/details/82845279