datareader对象提供只读单向数据的快速传递,单向:您只能依次读取下一条数据;只读:DataReader中的数据是只读的,不能修改;相对地,DataSet中的数据可以任意读取和修改

01.using (SqlConnection connection = 
02. new SqlConnection(connectionString)) 
03.{ 
04. SqlCommand command = 
05. new SqlCommand(queryString, connection); 
06. connection.Open(); 
07. 
08. SqlDataReader reader = command.ExecuteReader(); 
09. 
10. // 判断数据是否读到尾. 
11. while (reader.Read()) 
12. { 
13. Console.WriteLine(String.Format("{0}, {1}", 
14. reader[0], reader[1])); 
15. } 
16. 
17. // 一定要关闭 reader 对象. 
18. reader.Close(); 
19.}

SqlDataReader对象GetOrdinal()方法可以查看序列号的值
01.SqlCommand cmd = new SqlCommand(); 
02.//存储过程应用 
03.cmd.Connection = conn; 
04.cmd.CommandType = CommandType.StoredProcedure; 
05.cmd.CommandText = "ListTable"; 
06.cmd.Parameters.AddWithValue("@fileName", "ClsName, Sort"); 
07.cmd.Parameters.AddWithValue("@tableName", "Class"); 
08.cmd.Parameters.AddWithValue("@Sort", null); 
09.cmd.Parameters.AddWithValue("@whereStr", "ID < 10"); 
10.cmd.Parameters.AddWithValue("@groupStr", null); 
11.SqlDataReader rdr = cmd.ExecuteReader(); 
12.int intClsName = rdr.GetOrdinal("ClsName"); 
13.int intSort = rdr.GetOrdinal("Sort"); 
14. 
15.while (rdr.Read()) 
16.{ 
17. Console.WriteLine("ClsName : {0}, Sort:{1}", rdr[intClsName], rdr[intSort]); 
18. //可以调用SqlDataReader 的 Get 方法来避免由于装箱,拆箱而导致的性能损失 
19. Console.WriteLine("ClsName : {0}, Sort:{1}", rdr.GetString(intClsName), rdr.GetInt32(intSort)); 
20. //调用SqlDataReader 的 Get 方法在碰到 NULL 值时将会产生一个 SqlNullValueException.可以使用IsDBNull方法判断 
21. articleClass arc = new articleClass(); 
22. arc.clsname = rdr[0]; 
23. if (rdr.IsDBNull(rdr[1])) 
24. arc.sort = null; 
25. else 
26. arc.sort = rdr[1]; 
27. arc.clsname = rdr[1]; 
28. arc.Add(arc); 
29.} 
30.rdr.Close();

C# 数据库使用SqlCommand进行增,删,改,查询操作
using System;
using System.Collections.Generic;
using System.Text;

// We will make use of the SQL server
// provider, however it would also be
// permissible to make use of the ADO.NET
// factory pattern for greater flexibility.
using System.Data;
using System.Data.SqlClient;

namespace AutoLotConnectedLayer
{
public class InventoryDAL
{
#region Connection and Disconnection details.
// This member will be used by all methods.
private SqlConnection sqlCn = new SqlConnection();

public void OpenConnection(string connectionString)
{
sqlCn.ConnectionString = connectionString;
sqlCn.Open();
}
public void CloseConnection()
{
sqlCn.Close();
}
#endregion

#region Insert logic (both versions)
//public void InsertAuto(int id, string color, string make, string petName)
//{
// // Format and execute SQL statement.
// string sql = string.Format("Insert Into Inventory" +
// "(CarID, Make, Color, PetName) Values" +
// "('{0}', '{1}', '{2}', '{3}')", id, make, color, petName);
//
// // Execute using our connection.
// using(SqlCommand cmd = new SqlCommand(sql, this.sqlCn))
// {
// cmd.ExecuteNonQuery();
// }
//}

public void InsertAuto(int id, string color, string make, string petName)
{
// Note the 'placeholders' in the SQL query.
string sql = string.Format("Insert Into Inventory" +
"(CarID, Make, Color, PetName) Values" +
"(@CarID, @Make, @Color, @PetName)");

// This command will have internal parameters.
using (SqlCommand cmd = new SqlCommand(sql, this.sqlCn))
{
// Fill params collection.
SqlParameter param = new SqlParameter();
param.ParameterName = "@CarID";
param.Value = id;
param.SqlDbType = SqlDbType.Int;
cmd.Parameters.Add(param);

param = new SqlParameter();
param.ParameterName = "@Make";
param.Value = make;
param.SqlDbType = SqlDbType.Char;
param.Size = 10;
cmd.Parameters.Add(param);

param = new SqlParameter();
param.ParameterName = "@Color";
param.Value = color;
param.SqlDbType = SqlDbType.Char;
param.Size = 10;
cmd.Parameters.Add(param);

param = new SqlParameter();
param.ParameterName = "@PetName";
param.Value = petName;
param.SqlDbType = SqlDbType.Char;
param.Size = 10;
cmd.Parameters.Add(param);

cmd.ExecuteNonQuery();
}
}
#endregion

#region Delete logic
public void DeleteCar(int id)
{
// Get ID of car to delete, then do so.
string sql = string.Format("Delete from Inventory where CarID = '{0}'",
id);
using (SqlCommand cmd = new SqlCommand(sql, this.sqlCn))
{
try
{
cmd.ExecuteNonQuery();
}
catch (SqlException ex)
{
Exception error = new Exception("Sorry! That car is on order!", ex);
throw error;
}
}
}
#endregion

#region Update logic
public void UpdateCarPetName(int id, string newPetName)
{
// Get ID of car to modify and new pet name.
string sql =
string.Format("Update Inventory Set PetName = '{0}' Where CarID = '{1}'",
newPetName, id);
using (SqlCommand cmd = new SqlCommand(sql, this.sqlCn))
{
cmd.ExecuteNonQuery();
}
}
#endregion

#region Select logic
public DataTable GetAllInventory()
{
// This will hold the records. 
DataTable inv = new DataTable();

// Prep command object.
string sql = "Select * From Inventory";
using (SqlCommand cmd = new SqlCommand(sql, this.sqlCn))
{
SqlDataReader dr = cmd.ExecuteReader();
// Fill the DataTable with data from the reader and clean up.
inv.Load(dr);
dr.Close();
}
return inv;
}
#endregion

#region Trigger stored proc logic
public string LookUpPetName(int carID)
{
string carPetName = string.Empty;

// Establish name of stored proc.
using (SqlCommand cmd = new SqlCommand("GetPetName", this.sqlCn))
{
cmd.CommandType = CommandType.StoredProcedure;

// Input param.
SqlParameter param = new SqlParameter();
param.ParameterName = "@carID";
param.SqlDbType = SqlDbType.Int;
param.Value = carID;
param.Direction = ParameterDirection.Input;
cmd.Parameters.Add(param);

// Output param.
param = new SqlParameter();
param.ParameterName = "@petName";
param.SqlDbType = SqlDbType.Char;
param.Size = 10;
param.Direction = ParameterDirection.Output;
cmd.Parameters.Add(param);

// Execute the stored proc.
cmd.ExecuteNonQuery();

// Return output param.
carPetName = ((string)cmd.Parameters["@petName"].Value).Trim();
}
return carPetName;
}
#endregion

#region Tx Method
// A new member of the InventoryDAL class.
public void ProcessCreditRisk(bool throwEx, int custID)
{
// First, look up current name based on customer ID.
string fName = string.Empty;
string lName = string.Empty;

SqlCommand cmdSelect = new SqlCommand(
string.Format("Select * from Customers where CustID = {0}", custID), sqlCn);
using (SqlDataReader dr = cmdSelect.ExecuteReader())
{
while (dr.Read())
{
fName = (string)dr["FirstName"];
lName = (string)dr["LastName"];
}
}

// Create command objects which represent each step of the operation.
SqlCommand cmdRemove = new SqlCommand(
string.Format("Delete from Customers where CustID = {0}", custID), sqlCn);

SqlCommand cmdInsert = new SqlCommand(string.Format("Insert Into CreditRisks" +
"(CustID, FirstName, LastName) Values" +
"({0}, '{1}', '{2}')", custID, fName, lName), sqlCn);

// We will get this from the Connection object.
SqlTransaction tx = null;
try
{
tx = sqlCn.BeginTransaction();

// Enlist the commands into this transaction.
cmdInsert.Transaction = tx;
cmdRemove.Transaction = tx;

// Execute the commands.
cmdInsert.ExecuteNonQuery();
cmdRemove.ExecuteNonQuery();

// Simulate error.
if (throwEx)
{
throw new ApplicationException("Sorry! Database error! Tx failed...");
}

// Commit it!
tx.Commit();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
// Any error will rollback transaction.
tx.Rollback();

SqlCommand 对象的 ExecuteScalar 方法返回一个 Object 数据类型中第一行第一列的值。

view plaincopy to clipboardprint?
01.SqlCommand cmd = new SqlCommand(); 
02.//存储过程应用 
03.cmd.Connection = conn; 
04.cmd.CommandType = CommandType.StoredProcedure; 
05.cmd.CommandText = "ListTable"; 
06.cmd.Parameters.AddWithValue("@fileName", "top 1 ID"); 
07.cmd.Parameters.AddWithValue("@tableName", "Class"); 
08.cmd.Parameters.AddWithValue("@Sort", null); 
09.cmd.Parameters.AddWithValue("@whereStr", "ID < 4"); 
10.cmd.Parameters.AddWithValue("@groupStr", null); 
11.//可以直接使用 object Obj = cmd.ExecuteScalar(); 然后判断 Obj == null 并进行下步操作 
12.int ClassID = (int)cmd.ExecuteScalar(); 
13.Console.WriteLine(ClassID);

ExecuteNonQuery执行不返回结果集的查询,SqlCommand 对象的 ExecuteNonQuery 方法

view plaincopy to clipboardprint?
01.string UPDATE_SP = "update class set clsname = @ClassName where id = @ClassID"; 
02.SqlCommand cmd = new SqlCommand(UPDATE_SP, conn); 
03.SqlParameter[] p = new SqlParameter[2]{ 
04. new SqlParameter("@ClassName", DbType.String), 
05. new SqlParameter("@ClassID", DbType.Int32) 
06.}; 
07.p[0].Value = "Ado.Net"; 
08.p[1].Value = 7; 
09. 
10.foreach (SqlParameter parm in p) 
11. cmd.Parameters.Add(p); 
12. 
13.int ExecuteNum = cmd.ExecuteNonQuery(); 
14.Console.WriteLine(ExecuteNum);

Parameters参数化查询

,上述代码中已经实现参数化查询。Parameters 的作用可有效防止注入。利用AddWithValue 方法把参数传递给 cmd 对象。SqlParameter 对象详解

view plaincopy to clipboardprint?
01.//SqlParameter 对象,利用SqlCommand AddWithValue方法创建 同等于下面 
02.cmd.Parameters.AddWithValue("@ClassID", 3); 
03. 
04.//SqlParameter 对象 
05.SqlParameter p = new SqlParameter("@ClassID", DbType.Int16); 
06.p.Value = 3; 
07.cmd.Parameters.Add(p);

批量操作查询

,用StatementCompleted事件获取批量操作查询时个语句返回的影响数

view plaincopy to clipboardprint?
01.static void HandleStatementCompleted(object sender, StatementCompletedEventArgs e) 
02.{ 
03. Console.WriteLine("查询影响:{0} row(s)", e.RecordCount); 
04.} 
05.//.......................................... 
06.string SQL = "update class set num = 1 where id = 3;" + 
07. "update class set num = 2 where id = 4;" + 
08. "update class set num = 3 where id = 5;" + 
09. "update class set num = 4 where id = 6;"; 
10.SqlCommand cmd = new SqlCommand(SQL, conn); 
11.cmd.StatementCompleted += new StatementCompletedEventHandler(HandleStatementCompleted); 
12.int ExecuteNum = cmd.ExecuteNonQuery(); 
13.Console.WriteLine("批量查询共影响:{0} row(s)", ExecuteNum); 
14. 
15.//输出来自查询的多个结果集 
16.do { 
17. while (rdr.Read()) 
18. Console.WriteLine("{0} - {1}", rdr[0], rdr[1]); 
19. 
20.} while (rdr.NextResult());

执行异步查询,SqlCommand公开了Begin, End方法,例如:BeginExecuteReader, EndExecuteReader方法

每个 Begin 方法返回一个实现 IAsyncResult 接口对象。这一返回对象是查询状态的一个句柄,IAsyncResult 接口是用于异步方法的.NET Framework 模式的一部分,其设计目的:帮助确定该操作是否已经完成如果需要等待该操作完成则中断当前线程;用作方法调用的句柄。 IAsyncResult 接口的IsCompleted 属性,以查看 BeginExecuteReader 调用是否已经完成。调用IAsyncResult.AsyncWaitHandle.WaitOne 使用IAsyncResult接口来等待该调用完成 。

view plaincopy to clipboardprint?
01.using System.Threading; //需引用此命名空间 
02. 
03.conn.Open(); 
04.string SQL = "waitfor delay '00:00:10' ;" + 
05. "select * from class"; 
06.SqlCommand cmd = new SqlCommand(SQL, conn); 
07.IAsyncResult iar = cmd.BeginExecuteReader(); 
08.Console.WriteLine("异步查询是否已经获取记录?"); 
09.while (!iar.IsCompleted) 
10.{ 
11. Console.WriteLine("否,还在等待."); 
12. iar.AsyncWaitHandle.WaitOne(1000, true); 
13.} 
14.Console.WriteLine("是,已经获取数据."); 
15. 
16.SqlDataReader rdr = cmd.EndExecuteReader(iar); 
17.while (rdr.Read()) 
18.{ 
19. Console.WriteLine(rdr["ClsName"]); 
20.} 
21.rdr.Close();

SqlDataReader的用法 转自https://www.cnblogs.com/sunxi/p/3924954.html的更多相关文章

  1. sscanf 与 ssprintf 用法 (转载--https://www.cnblogs.com/Anker/p/3351168.html)

    sprintf函数 sprintf函数原型为 int sprintf(char *str, const char *format, ...).作用是格式化字符串,具体功能如下所示: (1)将数字变量转 ...

  2. 【redis】redis五大类 用法 【转载:https://www.cnblogs.com/yanan7890/p/6617305.html】

    转载地址:https://www.cnblogs.com/yanan7890/p/6617305.html

  3. Python中的logging模块【转】https://www.cnblogs.com/yelin/p/6600325.html

    [转]https://www.cnblogs.com/yelin/p/6600325.html 基本用法 下面的代码展示了logging最基本的用法. 1 # -*- coding: utf-8 -* ...

  4. 访问路径:https://i.cnblogs.com/posts?categoryid=925678

    https://i.cnblogs.com/posts?categoryid=925678

  5. URL https://i.cnblogs.com/EditPosts.aspx?opt=1

    URL url = new URL("https://i.cnblogs.com");URL url1 = new URL(url, "EditPosts.aspx?op ...

  6. 随笔二-https://www.cnblogs.com/shang1680/p/9657994.html

    作业要求来自https://edu.cnblogs.com/campus/gzcc/GZCC-16SE2/homework/2097 GitHub远程仓库的地址:https://github.com/ ...

  7. 211806189杨昊辰 https://www.cnblogs.com/honey1433223/

    211806189杨昊辰 https://www.cnblogs.com/honey1433223/

  8. https://www.cnblogs.com/h2zZhou/p/5440271.html

    https://www.cnblogs.com/h2zZhou/p/5440271.html

  9. https://www.cnblogs.com/soundcode/p/4174410.html

    https://www.cnblogs.com/soundcode/p/4174410.html 1.首先要在服务器端新建一个网站axpx页 然后再网站的后台写代码获取winform传过来的文件名. ...

随机推荐

  1. [转] css3制作图形大全

    Square   #square {     width: 100px;     height: 100px;     background: red; } Rectangle   #rectangl ...

  2. eclipse 配置maven tomcat 环境

    一  maven配置文件路径 二  tomcat 和JRE位置 三 validation 设置 四 五 六 设置run(debug) configurations 七 添加server时添加 reso ...

  3. MVVM讲解

    一,MVVM理论知识 从上一篇文章中,我们已经知道,WPF技术的主要特点是数据驱动UI,所以在使用WPF技术开发的过程中是以数据为核心的,WPF提供了数据绑定机制,当数据发生变化时,WPF会自动发出通 ...

  4. C#使用拉依达准则(3σ准则)剔除异常数据(.Net剔除一组数据中的奇异值)

    原文:C#使用拉依达准则(3σ准则)剔除异常数据(.Net剔除一组数据中的奇异值) 1.问题的提出: 电池生产中,遇到一批电池的测量结果数据: 电压值 电池个数 电压值 电池个数 电压值 电池个数 电 ...

  5. C# WindowsPrincipal(Windows规则)的使用

    using System;using System.Collections.Generic;using System.Linq;using System.Security.Principal;usin ...

  6. c# WebApi POST请求同时包含数据及其文件

    原因:创建.net WebApi的接口API.IIS作为服务端.安卓作为客户端发送json文件及其文件. Android端使用xUtils3.0实现文件上传 java代码: //要传递给服务器的jso ...

  7. .NET与 java通用的3DES加密解密方法

    C#代码 private void button1_Click(object sender, EventArgs e) { string jiami = textBox1.Text; textBox2 ...

  8. 【Python】wifi开关测试

    #!/usr/bin/python # -*- coding: UTF-8 -*- import os import time def find_device(): os.system('adb ki ...

  9. Pytorch Code积累

    2017 Python最新面试题及答案16道题 15个重要Python面试题 测测你适不适合做Python? torch.squeeze() Returns a tensor with all the ...

  10. 破处在window7桌面版本下golang连接数上限

    注册表 HKLM\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters 修改或者添加 MaxUserPort 60000 TcpTimedWaitDel ...