C#使用Ado.Net读写数据库
1.使用DataReader方式读取资料
- String connString = ConfigurationManager.ConnectionStrings["astt"].ConnectionString;
- //如果数据库连接字符串有加密,可以经过解密后重新获得连接字符串
- DbConnectionStringBuilder connBuilder = new DbConnectionStringBuilder();
- connBuilder.ConnectionString = connString;
- connBuilder["Data Source"] = connBuilder["Data Source"]; //可加上解密方法
- connBuilder["User ID"] = connBuilder["User ID"]; //可加上解密方法
- connBuilder["Password"] = connBuilder["Password"]; //可加上解密方法
- connString = connBuilder.ConnectionString;
- using (OleDbConnection conn = new OleDbConnection(connString))
- {
- try
- {
- conn.Open();
- using (OleDbCommand cmd = new OleDbCommand())
- {
- cmd.CommandText = "select * from s_userm where rownum <= ?";
- cmd.CommandType = CommandType.Text;
- cmd.Connection = conn;
- cmd.Parameters.Add("?", OleDbType.Integer).Value = 5; //cmd.Parameters.Add(new OleDbParameter("?", 5));
- using (OleDbDataReader reader = cmd.ExecuteReader())
- {
- while (reader.Read())
- {
- MessageBox.Show(reader.GetString(1), "资料");
- }
- }
- }
- conn.Close();
- }
- catch (Exception ex)
- {
- MessageBox.Show(ex.Message, "error");
- return;
- }
- }
2.使用DataAdapter与DataSet方式读取资料.
- String connString = ConfigurationManager.ConnectionStrings["astt"].ConnectionString;
- using (OleDbConnection conn = new OleDbConnection(connString))
- {
- try
- {
- using (OleDbCommand cmd = new OleDbCommand())
- {
- cmd.CommandText = "select * from s_userm where rownum <= ?";
- cmd.CommandType = CommandType.Text;
- cmd.Connection = conn;
- cmd.Parameters.Add("?", OleDbType.Integer).Value = 5; //cmd.Parameters.Add(new OleDbParameter("?", 5));
- DataSet ds = new DataSet();
- OleDbDataAdapter adapter = new OleDbDataAdapter(cmd);
- adapter.Fill(ds, "s_userm");
- foreach (DataRow dr in ds.Tables[0].Rows)
- {
- MessageBox.Show(Convert.ToString(dr["user_nm"]), "资料");
- }
- //listBox1.DataSource = ds.Tables[0].DefaultView;
- //listBox1.DisplayMember = "user_nm";
- //listBox1.ValueMember = "user_no";
- listBox1.DataSource = ds;
- listBox1.DisplayMember = "s_userm.user_nm";
- listBox1.ValueMember = "s_userm.user_no";
- dataGridView1.DataSource = ds.Tables[0].DefaultView;
- dataGridView1.ReadOnly = true;
- }
- }
- catch (Exception ex)
- {
- MessageBox.Show(ex.Message, "error");
- return;
- }
- }
3.使用DataAdapter与DataSet对单表的增删改查,根据Command的查询语法,使用CommandBuilder自动生成增删改的语法.
- String connString = ConfigurationManager.ConnectionStrings["astt"].ConnectionString;
- using (OleDbConnection conn = new OleDbConnection(connString))
- {
- OleDbCommand cmd = new OleDbCommand();
- cmd.CommandText = "select * from s_userm where rownum <= ?";
- cmd.CommandType = CommandType.Text;
- cmd.Connection = conn;
- cmd.Parameters.Add("?", OleDbType.Integer).Value = 5;
- OleDbDataAdapter adapter = new OleDbDataAdapter(cmd);
- //使用DataAdapter更新单表,可以使用CommandBuilder来自动生成InsertCommand,UpdateCommand,DeleteCommand
- OleDbCommandBuilder cmdbuilder = new OleDbCommandBuilder(adapter); //将自动生成InsertCommand,UpdateCommand,DeleteCommand
- MessageBox.Show(cmdbuilder.GetUpdateCommand().CommandText, "updcommand");
- //select
- DataSet ds = new DataSet();
- adapter.Fill(ds,"s_userm");
- dataGridView1.DataSource = ds.Tables["s_userm"].DefaultView;
- //insert
- DataRow updateRow = ds.Tables["s_userm"].NewRow();
- updateRow["user_no"] = "TEST1";
- updateRow["user_nm"] = "test1";
- ds.Tables["s_userm"].Rows.Add(updateRow);
- adapter.Update(ds, "s_userm");
- MessageBox.Show(Convert.ToString(ds.Tables["s_userm"].Rows[0]["user_no"]), "user");
- //update
- ds.Tables[0].Rows[1]["EMAIL"] = "gymsoft@163.com";
- adapter.Update(ds, "s_userm");
- //delete
- ds.Tables["s_userm"].Rows[0].Delete();
- adapter.Update(ds, "s_userm");
- }
4.使用DataAdapter与DataSet进行增删改查,手动指定增删改查的语法。
- String connString = ConfigurationManager.ConnectionStrings["astt"].ConnectionString;
- using (OleDbConnection conn = new OleDbConnection(connString))
- {
- DataSet ds = new DataSet();
- OleDbDataAdapter adapter = new OleDbDataAdapter();
- //指定DataAdapter的select语句
- OleDbCommand selectCmd = new OleDbCommand();
- selectCmd.CommandText = "select * from s_userm where rownum <= ?";
- selectCmd.CommandType = CommandType.Text;
- selectCmd.Connection = conn;
- selectCmd.Parameters.Add("?", OleDbType.Integer).Value = 5;
- adapter.SelectCommand = selectCmd;
- //指定DataAdapter的Insert语句
- OleDbCommand insertCmd = new OleDbCommand();
- insertCmd.CommandText = "insert into s_userm(user_no,user_nm) values(?,?)";
- insertCmd.CommandType = CommandType.Text;
- insertCmd.Connection = conn;
- insertCmd.Parameters.Add("?", OleDbType.VarChar, 30, "user_no");
- insertCmd.Parameters.Add("?", OleDbType.VarChar, 80, "user_nm");
- adapter.InsertCommand = insertCmd;
- //指定DataAdapter的Update语句
- OleDbCommand updateCmd = new OleDbCommand();
- updateCmd.CommandText = "update s_userm set email = ? where user_no = ?";
- updateCmd.CommandType = CommandType.Text;
- updateCmd.Connection = conn;
- updateCmd.Parameters.Add("?", OleDbType.VarChar, 50, "email");
- OleDbParameter parmUpdPk = updateCmd.Parameters.Add("?", OleDbType.VarChar, 30, "user_no");
- parmUpdPk.SourceVersion = DataRowVersion.Original;
- adapter.UpdateCommand = updateCmd;
- //指定DataAdapter的Delete语句
- OleDbCommand deleteCmd = new OleDbCommand();
- deleteCmd.CommandText = "delete from s_userm where user_no = ?";
- deleteCmd.CommandType = CommandType.Text;
- deleteCmd.Connection = conn;
- OleDbParameter parmDelPk = deleteCmd.Parameters.Add("?", OleDbType.VarChar, 30, "user_no");
- parmDelPk.SourceVersion = DataRowVersion.Original;
- adapter.DeleteCommand = deleteCmd;
- MessageBox.Show(adapter.SelectCommand.CommandText, "command");
- //select
- adapter.Fill(ds, "s_userm");
- dataGridView1.DataSource = ds.Tables["s_userm"].DefaultView;
- //insert
- DataRow updateRow = ds.Tables["s_userm"].NewRow();
- updateRow["user_no"] = "TEST2";
- updateRow["user_nm"] = "test2";
- ds.Tables["s_userm"].Rows.Add(updateRow);
- adapter.Update(ds, "s_userm");
- MessageBox.Show(Convert.ToString(ds.Tables["s_userm"].Rows[3]["user_no"]), "user");
- //update
- ds.Tables[0].Rows[3]["EMAIL"] = "gymsoft@163.com";
- adapter.Update(ds, "s_userm");
- //delete
- ds.Tables["s_userm"].Rows[3].Delete();
- adapter.Update(ds, "s_userm");
- }
5.使用DataGridView绑定数据源进行编辑,使用DataAdapter与DataSet进行增删改查,手动指定增删改查的语法。
- public partial class Form1 : Form
- {
- String connString;
- OleDbConnection conn;
- DataSet ds;
- OleDbDataAdapter adapter;
- public Form1()
- {
- InitializeComponent();
- }
- private void buttonQuery_Click(object sender, EventArgs e)
- {
- connString = ConfigurationManager.ConnectionStrings["astt"].ConnectionString;
- conn = new OleDbConnection(connString);
- ds = new DataSet();
- adapter = new OleDbDataAdapter();
- //指定DataAdapter的select语句
- OleDbCommand selectCmd = new OleDbCommand();
- selectCmd.CommandText = "select * from s_userm where rownum <= ?";
- selectCmd.CommandType = CommandType.Text;
- selectCmd.Connection = conn;
- selectCmd.Parameters.Add("?", OleDbType.Integer).Value = 5;
- adapter.SelectCommand = selectCmd;
- //指定DataAdapter的Insert语句
- OleDbCommand insertCmd = new OleDbCommand();
- insertCmd.CommandText = "insert into s_userm(user_no,user_nm) values(?,?)";
- insertCmd.CommandType = CommandType.Text;
- insertCmd.Connection = conn;
- insertCmd.Parameters.Add("?", OleDbType.VarChar, 30, "user_no");
- insertCmd.Parameters.Add("?", OleDbType.VarChar, 80, "user_nm");
- adapter.InsertCommand = insertCmd;
- //指定DataAdapter的Update语句
- OleDbCommand updateCmd = new OleDbCommand();
- updateCmd.CommandText = "update s_userm set email = ? where user_no = ?";
- updateCmd.CommandType = CommandType.Text;
- updateCmd.Connection = conn;
- updateCmd.Parameters.Add("?", OleDbType.VarChar, 50, "email");
- OleDbParameter parmUpdPk = updateCmd.Parameters.Add("?", OleDbType.VarChar, 30, "user_no");
- parmUpdPk.SourceVersion = DataRowVersion.Original;
- adapter.UpdateCommand = updateCmd;
- //指定DataAdapter的Delete语句
- OleDbCommand deleteCmd = new OleDbCommand();
- deleteCmd.CommandText = "delete from s_userm where user_no = ?";
- deleteCmd.CommandType = CommandType.Text;
- deleteCmd.Connection = conn;
- OleDbParameter parmDelPk = deleteCmd.Parameters.Add("?", OleDbType.VarChar, 30, "user_no");
- parmDelPk.SourceVersion = DataRowVersion.Original;
- adapter.DeleteCommand = deleteCmd;
- //MessageBox.Show(adapter.SelectCommand.CommandText, "command");
- //select
- adapter.Fill(ds, "s_userm");
- dataGridView1.DataSource = ds.Tables["s_userm"].DefaultView;
- }
- private void buttonSave_Click(object sender, EventArgs e)
- {
- adapter.Update(ds, "s_userm");
- ds.Clear();
- adapter.Fill(ds, "s_userm");
- dataGridView1.DataSource = ds.Tables["s_userm"].DefaultView;
- }
- }
6.使用DataAdapter与DataSet,以事务的方式进行增删改查。
- String connString = ConfigurationManager.ConnectionStrings["astt"].ConnectionString;
- using (OleDbConnection conn = new OleDbConnection(connString))
- {
- DataSet ds = new DataSet();
- OleDbDataAdapter adapter = new OleDbDataAdapter();
- //指定DataAdapter的select语句
- OleDbCommand selectCmd = new OleDbCommand();
- selectCmd.CommandText = "select * from s_userm where rownum <= ?";
- selectCmd.CommandType = CommandType.Text;
- selectCmd.Connection = conn;
- selectCmd.Parameters.Add("?", OleDbType.Integer).Value = 5;
- adapter.SelectCommand = selectCmd;
- //指定DataAdapter的Insert语句
- OleDbCommand insertCmd = new OleDbCommand();
- insertCmd.CommandText = "insert into s_userm(user_no,user_nm) values(?,?)";
- insertCmd.CommandType = CommandType.Text;
- insertCmd.Connection = conn;
- insertCmd.Parameters.Add("?", OleDbType.VarChar, 30, "user_no");
- insertCmd.Parameters.Add("?", OleDbType.VarChar, 80, "user_nm");
- adapter.InsertCommand = insertCmd;
- //指定DataAdapter的Update语句
- OleDbCommand updateCmd = new OleDbCommand();
- updateCmd.CommandText = "update s_userm set email = ? where user_no = ?";
- updateCmd.CommandType = CommandType.Text;
- updateCmd.Connection = conn;
- updateCmd.Parameters.Add("?", OleDbType.VarChar, 50, "email");
- OleDbParameter parmUpdPk = updateCmd.Parameters.Add("?", OleDbType.VarChar, 30, "user_no");
- parmUpdPk.SourceVersion = DataRowVersion.Original;
- adapter.UpdateCommand = updateCmd;
- //指定DataAdapter的Delete语句
- OleDbCommand deleteCmd = new OleDbCommand();
- deleteCmd.CommandText = "delete from s_userm where user_no = ?";
- deleteCmd.CommandType = CommandType.Text;
- deleteCmd.Connection = conn;
- OleDbParameter parmDelPk = deleteCmd.Parameters.Add("?", OleDbType.VarChar, 30, "user_no");
- parmDelPk.SourceVersion = DataRowVersion.Original;
- adapter.DeleteCommand = deleteCmd;
- //MessageBox.Show(adapter.SelectCommand.CommandText, "command");
- conn.Open();
- using (OleDbTransaction tran = conn.BeginTransaction(IsolationLevel.ReadCommitted))
- {
- adapter.SelectCommand.Transaction = tran;
- adapter.InsertCommand.Transaction = tran;
- adapter.UpdateCommand.Transaction = tran;
- adapter.DeleteCommand.Transaction = tran;
- try
- {
- //select
- adapter.Fill(ds, "s_userm");
- dataGridView1.DataSource = ds.Tables["s_userm"].DefaultView;
- //insert
- DataRow updateRow = ds.Tables["s_userm"].NewRow();
- updateRow["user_no"] = "TEST2";
- updateRow["user_nm"] = "test2";
- ds.Tables["s_userm"].Rows.Add(updateRow);
- adapter.Update(ds, "s_userm");
- //MessageBox.Show(Convert.ToString(ds.Tables["s_userm"].Rows[3]["user_no"]), "user");
- //update
- ds.Tables[0].Rows[3]["EMAIL"] = "gymsoft@163.com";
- adapter.Update(ds, "s_userm");
- //delete
- ds.Tables["s_userm"].Rows[3].Delete();
- adapter.Update(ds, "s_userm");
- tran.Commit();
- }
- catch (Exception ex)
- {
- try
- {
- tran.Rollback();
- }
- catch (Exception exc)
- {
- MessageBox.Show(exc.Message, "error");
- }
- MessageBox.Show(ex.Message, "error");
- }
- }
- conn.Close();
- }
C#使用Ado.Net读写数据库的更多相关文章
- .NET基础拾遗(6)ADO.NET与数据库开发基础
Index : (1)类型语法.内存管理和垃圾回收基础 (2)面向对象的实现和异常的处理 (3)字符串.集合与流 (4)委托.事件.反射与特性 (5)多线程开发基础 (6)ADO.NET与数据库开发基 ...
- .NET基础拾遗(8)ADO.NET与数据库开发基础
1.1 ADO.NET支持哪几种数据源? ① System.Data.SqlClient .NET程序员最常用的了.通过OLEDB或者ODBC都可以访问,但是SqlClient下的组件直接针对MSSQ ...
- Delphi通过ADO读写数据库
ADO是一种程序对象,用于表示用户数据库中的数据结构和所包含的数据. ADO (ActiveX Data Objects,ActiveX数据对象)是Microsoft提出的应用程序接口(API)用以实 ...
- Wcf for wp8 连接数据库,读写数据库,显示数据库数据(二)
下载: Microsoft® SQL Server® 2012 Express http://www.microsoft.com/zh-cn/download/details.aspx?id=2906 ...
- ADO访问Access数据库错误解决心得随笔
最近在用ADO访问Access数据库的时候出现了一个奇怪的错误,觉得有必要记录下来,和大家分享一下. 环境 win7 x86系统: VS2012编译器: Office2010: Access2000~ ...
- ado无法访问数据库问题
现象:以ADO方式访问数据库的C++程序,在一台计算机上能访问成功,在另一台计算机上却访问不成功,报告不能连接错误,并且这两台计算机都装有ado. 原因:ado版本不对 解决方案:下载KB983246 ...
- 浅析ado.net获取数据库元数据信息 DeriveParameters
写这个文章源于早先对ADO.Net获取数据库元数据上的认识,去年我在阅读ADO.Net Core Reference的时候曾经注意过DataSet的FillSchema的这个方法.这方面,在我之前的随 ...
- MFC,ADO方式实现数据库操作
参考: MSDN数据访问编程 (MFC/ATL): https://msdn.microsoft.com/zh-cn/library/kd4ck1tt.aspx?f=255&MSPPError ...
- 使用 ado.net访问数据库
一.ADO.NET :用于连接数据库的技术 1.ADO.NET分为两大组件 DataSet:数据集 .NET FRAMWORK :用于连接到数据库,发送命令,检索结果 2.ADO. ...
随机推荐
- 【2016.3.18】作业 VS2015安装&单元测试(2)
- Linux内核分析作业六
1.阅读理解task_struct数据结构 2.分析fork函数对应的内核处理过程sys_clone,理解创建一个新进程如何创建和修改task_struct数据结构: fork进程的代码 #inclu ...
- 广商博客冲刺第四五天new
第三天沖刺傳送門 第六七天沖刺傳送門 以上的前台设计架构已经完成了,现在来完成前台的安卓设计. 首先我们配置了Android SDK Manager 使得程序能在安卓环境下运行. 这就完成了前台安卓的 ...
- GitHub18
兴趣是最好的老师,HelloGitHub 就是帮你找到兴趣! 简介 分享 GitHub 上有趣.入门级的开源项目. 这是一个面向编程新手.热爱编程.对开源社区感兴趣 人群的月刊,月刊的内容包括:各种编 ...
- 9-Python3从入门到实战—基础之条件控制语句
Python从入门到实战系列--目录 条件判断 if 条件判断 if 语句语法 if <条件判断1>: <执行1> elif <条件判断2>: <执行2> ...
- [转帖] 数据库用优化方案 https://segmentfault.com/a/1190000006158186
Mysql大表优化方案 当MySQL单表记录数过大时,增删改查性能都会急剧下降,可以参考以下步骤来优化: 单表优化 除非单表数据未来会一直不断上涨,否则不要一开始就考虑拆分,拆分会带来逻辑.部 ...
- FICO基础知识(三)
成本中心: 成本中心是企业内的最小职责单位,是每一笔费用的具体接收者.创建成本中心主数据时必须将每个成本中心分配给标准层次结构的某个节点,标准层次结构反映了成本中心与成本中心.成本中心与成本中心组.成 ...
- 【Mysql】—— MySQL存储引擎中的MyISAM和InnoDB区别详解
在使用MySQL的过程中对MyISAM和InnoDB这两个概念存在了些疑问,到底两者引擎有何分别一直是存在我心中的疑问.为了解开这个谜题,搜寻了网络,找到了如下信息: MyISAM是MySQL的默认数 ...
- fatal error: matio.h: No such file or directory
http://blog.csdn.net/zziahgf/article/details/72900948 $ sudo apt-get install libmatio-dev 或源码安装: # 下 ...
- 读取excel思路
1.输入地址 2.输入指定的sheet 通过sheet()[]方式指定 3.输入执行的单元位置 通过 .cell_value(x,y)方式指定 示例 data = xlrd.open_workboo ...