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. ...
随机推荐
- Linux内核设计第十七章笔记
第十七章 设备与模块 关于设备驱动和设备管理,四种内核成分 设备类型:在所有unix系统中为了统一普通设备的操作所采用的分类 模块:Linux内核中用于按需加载和卸载目标代码的机制 内核对象:内核数据 ...
- 转发:Android开发?用C#!!
转发自 最近偶然在QQ技术群里见到有人提起用C#开发Android,当时我感觉到很诧异:Android不是只能用Java开发吗?何时可以使用C#了?那个群友便告知我:mono. 百度一下吧!搜到了mo ...
- FreeMaker使用HashMap
private Map<String, Object> variables; <input type="hidden" id="tongzhisbm&q ...
- Server Tomcat v7.0 Server at libra failed to start
https://stackoverflow.com/questions/13244233/server-tomcat-v7-0-server-at-localhost-failed-to-start- ...
- React onWheel
<!DOCTYPE html><html><head lang="en"> <meta charset="UTF-8" ...
- centos目录
cd /opt cd /home/lujie cd /etc cd /usr cd /dev cd /bin cd /mnt cd /media cd /tmp
- golang自定义struct字段标签
原文链接: https://sosedoff.com/2016/07/16/golang-struct-tags.html struct是golang中最常使用的变量类型之一,几乎每个地方都有使用,从 ...
- java构造函数总结
构造函数总结 概念: 创建对象时由JVM自动调用的函数 作用: 在创建对象的时候给对象的成员变量赋值: 写法: 修饰符:可以用访问权限修饰符(public.private等)修饰:不能用s ...
- Harmonic Number LightOJ - 1234 (分段打表)
题意: 求调和级数,但n很大啦.. 解析: 分段打表 每间隔50存储一个数,在计算时 只需要找到离输入的n最近的那个数 以它为起点 开始计算即可 emm...补充一下调和级数的运算公式 r为常 ...
- mysql 免安装版 启动服务马上关闭
在my.ini 加入这一句 1.直接在后面加上一下的参数 [mysqld] port=3306 basedir=D:\mysql-5.7.17-win32 datadir=D:\mysql-5.7.1 ...