Step1:安装Mysql.Data程序包
右键项目名->管理Nuget程序包,安装MySql.Data程序包
Step2: 代码
using MySql.Data.MySqlClient;
namespace ConConSql
{
internal class Program
{
static void Main(string[] args)
{
var builder = new MySqlConnectionStringBuilder();
builder.Server = "localhost";
builder.Port = 3306;
builder.UserID = "root";
builder.Password ="123456";
builder.Database = "cargodbtest";
// builder.ConnectionString是把上面设置的属性整体连接为一个字符串
var connect = new MySqlConnection(builder.ConnectionString);
// 打开连接对象
connect.Open();
// 提供命令
var cmd = "Show databases;";
var reader = new MySqlCommand(cmd,connect).ExecuteReader(); // 要执行的语句是查询语句用ExecuteReader
while (reader.Read())
{
//下面三个是等价的
Console.WriteLine(reader.GetString(0));
//Console.WriteLine(reader[0]);
//Console.WriteLine(reader["Database"]);
}
// 关闭读取器
reader.Close();
// 可以再执行其他命令
cmd = "Create Table if not Exists myNewTable(id int, name varchar(20))";
new MySqlCommand(cmd, connect).ExecuteNonQuery(); //要执行的语句不是查询语句用ExecuteNonQuery
}
}
}