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.4.6】结对编程 终章 THE END
- 【实践报告】Linux实践三
Linux实践——程序破解 一.掌握NOP.JNE.JE.JMP.CMP汇编指令的机器码 NOP:NOP指令即“空指令”.执行到NOP指令时,CPU什么也不做,仅仅当做一个指令执行过去并继续执行NOP ...
- Linux 实验一 基础实践
Linux 实践一 1:软件源的维护方法 删掉DEB打头的 在命令行中输入命令时,可以用命令补全的方法. 下载完成后,使用sudo dpkg-i skype.deb 来完成安装. 2:掌握Linux ...
- Leetcode——32.最长有效括号【##】
@author: ZZQ @software: PyCharm @file: leetcode32_最长有效括号.py @time: 2018/11/22 19:19 要求:给定一个只包含 '(' 和 ...
- 第一个Sprint
项目名字:四则运算APP 开发环境:java 团队名称:会飞的小鸟 团队成员:陈志棚 李炫宗 刘芮熔 徐侃 罗伟业 一.经过宿舍世纪讨论后我们剔除了一些不合理的设计,比如网站管理员这一部分在 ...
- HDU 2053 Switch Game
http://acm.hdu.edu.cn/showproblem.php?pid=2053 Problem Description There are many lamps in a line. A ...
- 传输层中的协议 TCP & UDP
面向连接的TCP协议 “面向连接”就是在正式通信前必须要与对方建立起连接.比如你给别人打电话,必须等线路接通了.对方拿起话筒才能相互通话.TCP(Transmission Control Protoc ...
- wps word改多级编号为2.1
右键标题1, 修改样式 编号 多级编号 标题1 2 3 右键标题2 修改样式 选择格式-编号 选择多级编号-标题1 2 3 直接点确定,OK. ---------------------------- ...
- Ionic3.x设置启动页与图标
由于手机有很多不同的尺寸与版本,所以图标尺寸也是大小不一,但是如果手动每一个尺寸都制作一个图标,那估计美工会吐血吧,不过幸好,ionic只需要一个图标就可以制作不同尺寸的图标. 添加一个ionic项目 ...
- Personal Software Process (PSP)
日期 分类 开始时间 结束时间 中断时间 净时间 活动 备注 C U 2016/03/15 随笔 9:30 10:40 0 70 博客更新 更新<软件项目管理(1)> Y Minute 随 ...