使用MySQL数据库前提是在电脑上安装好了MYSQL数据库,然后才能使用
1.下载MySql.Data.dll,MySql.Web.dll
MySql.Data.dll,MySql.Web.dll是C#操作MySQL的驱动文件,是C#连接MySQL必要插件。
2.新建一个windows窗体应用程序。
新建一个windows窗体应用程序MySQLConnectionTest,在界面上添加一个DataGridView,默认name为:dataGridView1。
3.添加MySql.Data.dll,MySql.Web.dll引用。
在解决方案资源管理器中选择项目MySQLConnectionTest——>右键——>添加引用
在弹出对话框中选择浏览——>找到MySql.Data.dll,MySql.Web.dll文件并选中两个文件,点击确定按钮。
添加引用成功后可以在引用中查看到两个dll文件
4.添加代码实现。
双击Form1窗体,进入到Form1.cs代码界面,在Form1_Load函数中添加代码连接数据库并显示数据信息。
注:需要在MYSQL数据库中建好数据库select_test,以及在数据库select_test中的表teacher_table。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using MySql.Data.MySqlClient;//添加mysql引用
using System.Diagnostics;
namespace MySQLConnectionTest
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
//构建数据库连接字符串
string M_str_sqlcon = "server=localhost;user id=root;password=root;database=select_test"; //根据自己的设置
//创建数据库连接对象
MySqlConnection mycon = new MySqlConnection();
mycon.ConnectionString = M_str_sqlcon;
try
{
//打开数据库连接
mycon.Open();
MessageBox.Show("数据库已经连接了!");
string sql = "select * from teacher_table";
MySqlDataAdapter mda = new MySqlDataAdapter(sql, mycon);
DataSet ds = new DataSet();
mda.Fill(ds, "table1");
//显示数据
this.dataGridView1.DataSource = ds.Tables["table1"];
}
catch (Exception ex)
{
//MessageBox.Show(ex.Message);
Debug.Write(ex);
}
//关闭数据库连接
mycon.Close();
}
}
}
更多推荐
C#连接MySQL数据库——使用MySql.Data.dll
发布评论