SqlDataReader的用法 转自https://www.cnblogs.com/sunxi/p/3924954.html
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的更多相关文章
- sscanf 与 ssprintf 用法 (转载--https://www.cnblogs.com/Anker/p/3351168.html)
sprintf函数 sprintf函数原型为 int sprintf(char *str, const char *format, ...).作用是格式化字符串,具体功能如下所示: (1)将数字变量转 ...
- 【redis】redis五大类 用法 【转载:https://www.cnblogs.com/yanan7890/p/6617305.html】
转载地址:https://www.cnblogs.com/yanan7890/p/6617305.html
- Python中的logging模块【转】https://www.cnblogs.com/yelin/p/6600325.html
[转]https://www.cnblogs.com/yelin/p/6600325.html 基本用法 下面的代码展示了logging最基本的用法. 1 # -*- coding: utf-8 -* ...
- 访问路径:https://i.cnblogs.com/posts?categoryid=925678
https://i.cnblogs.com/posts?categoryid=925678
- 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 ...
- 随笔二-https://www.cnblogs.com/shang1680/p/9657994.html
作业要求来自https://edu.cnblogs.com/campus/gzcc/GZCC-16SE2/homework/2097 GitHub远程仓库的地址:https://github.com/ ...
- 211806189杨昊辰 https://www.cnblogs.com/honey1433223/
211806189杨昊辰 https://www.cnblogs.com/honey1433223/
- https://www.cnblogs.com/h2zZhou/p/5440271.html
https://www.cnblogs.com/h2zZhou/p/5440271.html
- https://www.cnblogs.com/soundcode/p/4174410.html
https://www.cnblogs.com/soundcode/p/4174410.html 1.首先要在服务器端新建一个网站axpx页 然后再网站的后台写代码获取winform传过来的文件名. ...
随机推荐
- wpf datagrid设置右键菜单打开时选中项的背景色
原文:wpf datagrid设置右键菜单打开时选中项的背景色 版权声明:本文为博主原创文章,未经博主允许不得转载. https://blog.csdn.net/huangli321456/artic ...
- 使用HANDLE_MSG宏简化Win32应用的开发
http://blog.csdn.net/daiyutage/article/details/17241161 Win32应用中的回调函数WndProc用于接收Windows向应用程序直接发送的消息, ...
- AngularJS ng-if使用
示例中,根据ng-if指令显示不同任务状态,以及判断任务是否可以操作 <div ng-app="NgifDemoApp" ng-controller="NgifDe ...
- XF 通过判断平台加载不同的图片
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.T ...
- Delphi 调用C/C++的Dll(stdcall关键字, 会导致函数名分裂. 此时函数名变成_stdadd@8)
delphi调用C++写的Dll, 当然这个Dll要求是非MFC的Dll, 这样子才能被delphi调用. 根据C++定义函数的情况, Delphi有不同的相对应的处理方法.1. 声明中不加__std ...
- redis zincrby zadd 遇到的问题
在维护代理池时 报错1: zincrby(REDIS_KEY,proxy,-1)redis.exceptions.ResponseError: value is not a valid float 查 ...
- dataGrid 源更新 事件
DataGrid myGrid = new DataGrid(); CollectionView myCollectionView = (CollectionView)CollectionViewSo ...
- GlusterFS集群文件系统研究(负载均衡的最常用办法) good
http://blog.csdn.net/liuaigui/article/details/6284551 http://blog.csdn.net/liuaigui/article/details/ ...
- python脚本,重新设置图片大小
最近在做一个android的电台,此android程序要访问自己服务器上的歌曲文件,包括图片.这些文件要自己手动上传. 每天十首歌,需要二十个图片(一个大图450*450.一个小图140*140). ...
- DBLINK学习
1.连接本地scott用户查看拥有的表 [oracle@ORADG ~]$ sqlplus scott/tiger SQL> select * from tab; TNAME ...