本文参考文档:http://download.youkuaiyun.com/detail/shawncheer/9494349
首先打开数据库,输入命令切换到world数据库;
use world;
再查看里面有什么:
select * from country;
发现里面的数据挺老的;
本文主要实现以下内容;
从数据库读取大块数据,并且显示在Grid View Control中,并且可以更新到数据库中;
用到以下几个工具;
DataSet----->DataAdapter----->CommandBuider;
有两个操作:
Fill 从数据库载入到程序中;
Updata 更新到数据库中;
以下是程序实现;
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;
using MySql.Data.MySqlClient;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
//Adapter是连接dataset和数据库的接口,有从数据表读入数据写到DataSet和修改后写回数据表的功能;
MySqlDataAdapter daCountry;
//DataSet是Windows的程序容器;
DataSet dsCountry;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
//Country是数据表
daCountry.Update(dsCountry, "Country");//将更改保存到数据库中;
label1.Text = "MySQL Database Updated!";
}
private void Form1_Load(object sender, EventArgs e)
{
string myConnectionString= "server=127.0.0.1;uid=root;" +
"pwd=1234;database=world";
//这个connection是要有的,但是conn.open()不是必须的;
MySqlConnection conn = new MySqlConnection(myConnectionString);
try
{
label1.Text = "Connecting to MySQL...";
string sql = "SELECT Code, Name, HeadOfState FROM Country WHERE Region='Eastern Asia'";
//When a MySqlDataAdapter object is created, it is typically given an initial SELECT statement.
daCountry = new MySqlDataAdapter(sql, conn);//创建一个接口,这个接口只接入Code, Name, HeadOfState三个字段,并且满足东亚的条件;
/*
* From this SELECT statement the Command Builder can work out the corresponding
* INSERT, UPDATE and DELETE statements that would be required to update the database.
*/
MySqlCommandBuilder cb = new MySqlCommandBuilder(daCountry);//实现对从数据接口Adapter对数据进行插入、更新、删除操作;
dsCountry = new DataSet();
//Country是数据表
daCountry.Fill(dsCountry, "Country");//将Country数据表中的几个字段的数据读入数据集中;
dataGridView1.DataSource = dsCountry;//将数据集作为显示的输入源;
dataGridView1.DataMember = "Country";//获取更改的元素;使得程序可以更改显示的数据,留着以后更新到数据库中;
}
catch (Exception ex)
{
label1.Text = ex.ToString();
}
}
}
}
下面是运行效果图:
修改几个文字后:
在MySQL数据库也更新了: