C#连接Mysql数据库与一些简单操作

要求

 数据库连接
1、请设计一个项目连接到自己的MySQL数据库,数据库包含至少三张表;
2、使用dataGridView控件显示表中的数据;
3、实现基本crud操作;



一、连接数据库

在Visual Studio 中打开数据库MySql

1.新建项目->工具 -> NuGet包管理器 ->管理解决方案的NuGet 程序包

2.浏览->搜索“MySql”

 3.选择第一个MySql.Data 安装到当前项目

 4.Vs连接数据库成功

            

二、简单操作的实现

1.窗体显示:添加dataGridView(显示表中的数据)和几个button控件

(1)添加dataGridView 选择(无)来显示表格信息,点击添加项目数据源,接着继续操作与自己数据库的有关内容连接

新建连接->选中MySql进添加

(2)添加相应button控件(详见最终窗体效果图),并更改相应属性,将按钮调至合适位置大小

 (3)最终窗体显示效果

2.相关代码

(1)测试连接数据库 

用户名和密码根据自己设置的更改,创建数据库连接的对象也要根据自己的数据库进行修改

string M_str_sqlcon = "server=localhost;user id=root;password=123456;database=sys";                                                                                              //创建数据库连接对象
			conn = new MySqlConnection(M_str_sqlcon);
			try
			{
				//打开数据库连接
				conn.Open();
				MessageBox.Show("数据库已经连接了!");
			}
			catch (Exception ex)
			{
				MessageBox.Show(ex.Message);
			}

(2)“显示数据”功能 

string sql = "select * from score";
			mda = new MySqlDataAdapter(sql, conn);
			ds = new DataSet();
			mda.Fill(ds, "score");
			//显示数据
			dataGridView1.DataSource = ds.Tables["score"];
			conn.Close();

(3)“添加”功能

if (mda == null || ds == null)
			{
				MessageBox.Show("请先导入数据");
				return;
			}
			try
			{
				string msg = "确实要添加此条数据吗?";
				if (1 == (int)MessageBox.Show(msg, "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Exclamation))
				{
					MySqlCommandBuilder builder = new MySqlCommandBuilder(mda);
					mda.Update(ds, "score");
					MessageBox.Show("添加成功", "提示");
				}
			}
			catch (Exception ex)
			{
				MessageBox.Show(ex.ToString(), "错误信息");
			}
 
		}

(4)“删除”功能

int count = 0;
			try
			{
				
				
				//for循环,dataGridView1.SelectedRows.Count为鼠标选中行的数目,一次for循环删除一行数据
				for (int i = 0; i < dataGridView1.SelectedRows.Count; i++)
				{
					//获得i行的编号
					int id = Convert.ToInt32(dataGridView1.SelectedRows[i].Cells[0].Value);
					//编写数据库删除代码,这里还用到了动态变量,用于改变每次id值
					string dataToDo3 = $"delete from student where id = {id}";
					MySqlCommand
										//创建MySqlCommand类用于SQL语句的执行
										cmd = new MySqlCommand(dataToDo3, conn);
					//定义x接收返回值SQL语句返回值,为0则为执行失败
					int x = cmd.ExecuteNonQuery();
					//执行判断
					if (x == 0)
					{
						MessageBox.Show("删除失败");
					}
					//若成功则计数值+1
					count = count + 1;
				}
				//若计数值等于选中行的数目,代表成功完成所有行的删除
				if (count == dataGridView1.SelectedRows.Count)
				{
					MessageBox.Show("删除成功");
				}
 
			}
			catch (Exception ex)
			{
 
				MessageBox.Show(ex.ToString());
			}
			finally
			{
				//这里是刷新界面
				button2.PerformClick();
			
				
			}
 
 
 
		}

(5)“修改”功能

if (mda == null || ds == null)
			{
				MessageBox.Show("请先导入数据");
				return;
			}
			try
			{
				string msg = "确实要修改吗?";
				if (1 == (int)MessageBox.Show(msg, "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Exclamation))
				{
					MySqlCommandBuilder builder = new MySqlCommandBuilder(mda); //命令生成器。
																				//适配器会自动更新用户在表上的操作到数据库中
					mda.Update(ds, "score");
					MessageBox.Show("修改成功", "提示");
				}
			}
			catch (Exception ex)
			{
				MessageBox.Show(ex.ToString(), "错误信息");
			}
 
		}

(6)退出

Application.Exit();

3.完整代码

using MySql.Data.MySqlClient;
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;
 
namespace 连接数据库
{
 
	public partial class Form1 : Form
	{
		MySqlConnection conn; //连接数据库对象
		MySqlDataAdapter mda; //适配器变量
		DataSet ds;  //临时数据集
 
		public Form1()
		{
			InitializeComponent();
		}
 
		private void Form1_Load(object sender, EventArgs e)
		{
 
 
		}
 
		private void button1_Click(object sender, EventArgs e)
		{
			string M_str_sqlcon = "server=localhost;user id=root;password=123456;database=sys";                                                                                              //创建数据库连接对象
			conn = new MySqlConnection(M_str_sqlcon);
			try
			{
				//打开数据库连接
				conn.Open();
				MessageBox.Show("数据库已经连接了!");
			}
			catch (Exception ex)
			{
				MessageBox.Show(ex.Message);
			}
 
		}
 
		private void sysDataSet1BindingSource_CurrentChanged(object sender, EventArgs e)
		{
 
		}
 
		private void button2_Click(object sender, EventArgs e)
		{
			string sql = "select * from score";
			mda = new MySqlDataAdapter(sql, conn);
			ds = new DataSet();
			mda.Fill(ds, "score");
			//显示数据
			dataGridView1.DataSource = ds.Tables["score"];
			conn.Close();
 
		}
 
		private void button5_Click(object sender, EventArgs e)
		{
 
			int count = 0;
			try
			{
				
				
				//for循环,dataGridView1.SelectedRows.Count为鼠标选中行的数目,一次for循环删除一行数据
				for (int i = 0; i < dataGridView1.SelectedRows.Count; i++)
				{
					//获得i行的编号
					int id = Convert.ToInt32(dataGridView1.SelectedRows[i].Cells[0].Value);
					//编写数据库删除代码,这里还用到了动态变量,用于改变每次id值
					string dataToDo3 = $"delete from student where id = {id}";
					MySqlCommand
										//创建MySqlCommand类用于SQL语句的执行
										cmd = new MySqlCommand(dataToDo3, conn);
					//定义x接收返回值SQL语句返回值,为0则为执行失败
					int x = cmd.ExecuteNonQuery();
					//执行判断
					if (x == 0)
					{
						MessageBox.Show("删除失败");
					}
					//若成功则计数值+1
					count = count + 1;
				}
				//若计数值等于选中行的数目,代表成功完成所有行的删除
				if (count == dataGridView1.SelectedRows.Count)
				{
					MessageBox.Show("删除成功");
				}
 
			}
			catch (Exception ex)
			{
 
				MessageBox.Show(ex.ToString());
			}
			finally
			{
				//这里是刷新界面
				button2.PerformClick();
			
				
			}
 
 
 
		}
 
		private void button4_Click(object sender, EventArgs e)
		{
			if (mda == null || ds == null)
			{
				MessageBox.Show("请先导入数据");
				return;
			}
			try
			{
				string msg = "确实要修改吗?";
				if (1 == (int)MessageBox.Show(msg, "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Exclamation))
				{
					MySqlCommandBuilder builder = new MySqlCommandBuilder(mda); //命令生成器。
																				//适配器会自动更新用户在表上的操作到数据库中
					mda.Update(ds, "score");
					MessageBox.Show("修改成功", "提示");
				}
			}
			catch (Exception ex)
			{
				MessageBox.Show(ex.ToString(), "错误信息");
			}
 
		}
 
		private void button3_Click(object sender, EventArgs e)
		{
			if (mda == null || ds == null)
			{
				MessageBox.Show("请先导入数据");
				return;
			}
			try
			{
				string msg = "确实要添加此条数据吗?";
				if (1 == (int)MessageBox.Show(msg, "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Exclamation))
				{
					MySqlCommandBuilder builder = new MySqlCommandBuilder(mda);
					mda.Update(ds, "score");
					MessageBox.Show("添加成功", "提示");
				}
			}
			catch (Exception ex)
			{
				MessageBox.Show(ex.ToString(), "错误信息");
			}
 
		}
 
		private void button6_Click(object sender, EventArgs e)
		{
			Application.Exit();
		}
	}
}

三、结果展示

1.数据库连接成功

2.点击 显示数据 后就能在DataGridView中看到选择的表格

3. 点击 删除 后可以删除表格信息

 四、总结

        因为我使用的是vs2022,刚开始连接数据库MySql,按照老师分享在群里的常规方法连接不上。后来是通过同学分享的方式连接成功。连接上MySql之后,会自动添加了一些有关的引用。接下来添加button并修改属性并不难,主要是DataGridView控件的使用是新内容。结合老师上课做的示范和我在网上搜索的例子,通过DataGridView控件达到了显示表中的数据的效果。

        实现基本crud操作,就需要一些不同功能代码段的“控件”,根据相应功能“检测连接”,“显示数据”,“添加”,“删除”,“修改”进行编写就行了。从而对数据库包含的三张表进行相应操作。总体来说本次实验进行的比较顺利,除了刚开始的连接数据库是尝试了多次,MySql的配置环境也花费了一些时间,对DataGridView控件的使用还比较熟练。通过这次实验,我学会了连接数据库和进行一些基本crud操作,体会到了C#窗体应用的多样和趣味性。

 五、github仓库地址

wmy-19/Database-connection: C#连接Mysql数据库与一些简单操作 (github.com)

  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值