vs用c#实现mysql数据库连接
本文主要介绍如何用vs连接数据库。
我所使用版本的是2017版的,其它版本不知道是否能用。下面是我在查阅了众多资料后整理出来的(文末已附原文链接),仅供参考
(1)新建windows窗体应用程序

(2)新建项目处右击选择管理NuGet程序包

(3)在浏览区搜索mysql.data,安装(如果无法安装,有可能是新建项目时项目的.Net Framework版本和mysql.data的版本不适配,可安装其它版本或新建项目)

点击安装即可,我这里已经安装成功了
(4)双击window窗体,引入using MySql.Data.MySqlClient;
(5)输入连接数据库的代码:以在Form1_Load为例,在private void Form1_Load(object sender, EventArgs e)中输入
MySqlConnection con = new MySqlConnection("server=localhost;port=3306;user=root;password=1;database=test;"); con.Open();//连接打开
Server为Mysql本地地址,一般默认localhost即本地,port为端口号,一般不用改,user和password为你本地数据库的用户名和密码,database为连接的数据库的名称(确保建立了这个数据库,否则会报错)
(6)查看数据库中的数据,接着上面的代码继续写:
MySqlCommand co = new MySqlCommand("select * from student;", con); MySqlDataAdapter adapt = new MySqlDataAdapter(); adapt.SelectCommand = co; DataSet ds = new DataSet(); adapt.Fill(ds, "t"); //第二个参数:表名,随便取 dataGridView1.DataSource = ds.Tables["t"]; con.Close();
,如图
(7)附加,实现curd基本操作
` MySqlCommand coo = new MySqlCommand("select * from student;", con);//输出数据
//MySqlCommand coo = new MySqlCommand("update student set s_name='李四' where s_id= '03'", con);//更新数据,将学号为03的姓名改成李四
//MySqlCommand coo = new MySqlCommand("insert into student values (12,'张三',25,'大专')", con);//插入学生数据“张三”
//MySqlCommand coo = new MySqlCommand("delete from student where s_id = '02'", con);//删除学号为02的学生数据
MySqlDataAdapter adapt = new MySqlDataAdapter();
adapt.SelectCommand = coo;
DataSet ds = new DataSet();
adapt.Fill(ds, "t");
dataGridView1.DataSource = ds.Tables["t"];
con.Close();`
输出结果如下:

完整代码如下:
`using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using MySql.Data.MySqlClient;
namespace shujukulianjie
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
MySqlConnection con = new MySqlConnection("server=localhost;port=3306;user=root;password=xxxx;database=xxxx;");
con.Open();
MySqlCommand coo = new MySqlCommand("select * from student;", con);
//MySqlCommand coo = new MySqlCommand("update student set s_name='李四' where s_id= '03'", con);
//MySqlCommand coo = new MySqlCommand("insert into student values (12,'张三',25,'大专')", con);
//MySqlCommand coo = new MySqlCommand("delete from student where s_id = '02'", con);
MySqlDataAdapter adapt = new MySqlDataAdapter();
adapt.SelectCommand = coo;
DataSet ds = new DataSet();
adapt.Fill(ds, "t"); //第二个参数:表名,随便取
dataGridView1.DataSource = ds.Tables["t"];
con.Close();
}
}
}`
仓库地址:https://gitee.com/assena/vs-connecting-to-mysql.git
相关资料:
https://blog.csdn.net/csdnanyway/article/details/115505276
https://blog.csdn.net/qq_39588003/article/details/103605803
https://www.cnblogs.com/ttkl/p/7730246.html

浙公网安备 33010602011771号