mysql+C#实战四:从数据库中读取数据块和更新数据;
2016-04-19 23:02
531 查看
本文参考文档:http://download.csdn.net/detail/shawncheer/9494349
首先打开数据库,输入命令切换到world数据库;
select * from country;
发现里面的数据挺老的;
本文主要实现以下内容;
从数据库读取大块数据,并且显示在Grid View Control中,并且可以更新到数据库中;
用到以下几个工具;
DataSet----->DataAdapter----->CommandBuider;
有两个操作:
Fill 从数据库载入到程序中;
Updata 更新到数据库中;
以下是程序实现;
下面是运行效果图:
修改几个文字后:
在MySQL数据库也更新了:
首先打开数据库,输入命令切换到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数据库也更新了:
相关文章推荐
- 跟我一起学习MySQL技术内幕(第五版):(第二章学习日记8)
- 数据库的基本操作(MySQL)
- 数据库mysql服务启动时提示:Windows无法启动服务,1069号错误
- MySQL 主从复制
- mysql主从
- mysql 查询,切换数据库
- MySQL常用函数
- mysql学习笔记(二)
- mysql常用语句
- mysql解压之后的安装
- mysqldump使用方法(MySQL数据库的备份与恢复)
- MySQL约束操作
- 高性能Mysql
- MySQL数据库MyISAM和InnoDB存储引擎的比较
- 通过mysqldump和SCP实现mysql定时自动备份到另外一台服务器脚本
- 个人总结-mysql错误
- mysql set name、set character set区别
- MySQL修改root密码的多种方法
- Mac操作系统下忘记MYSQL的密码--无密码进入
- MySQL分库分表环境下全局ID生成方案