Ado.net 介绍:使用参数化查询
以get方式传递参数.后获取参数当作条件合并到SQL语句中.查询想要的数据.
URL表现形式:http://www.cngothic.com/search.aspx?customerid=TOMSP
代码如下:

  1. SqlConnection conn = new SqlConnection();
  2. conn.ConnectionString = ConfigurationManager.ConnectionStrings["strcon"].ConnectionString;
  3. conn.Open();
  4. //打开数据库
  5. string SqlStr;
  6. SqlStr = "SELECT OrderID,CustomerID,OrderDate,EmployeeID FROM Orders WHERE CustomerID=@CustomerID";
  7. //带参数的SQL语句
  8. SqlCommand SqlCmd = new SqlCommand(SqlStr, conn);
  9. SqlCmd.Parameters.AddWithValue"("@CustomerID", TOMSP");
  10. //在customerid参数没有值的情况下为其赋个值为:TOMSP
  11. SqlDataReader redr = SqlCmd.ExecuteReader();
  12. while (redr.Read())
  13. {
  14. Response.Write(redr["OrderID"] + "<br />");
  15. Response.Write(Request.QueryString["CustomerID"]);
  16. }

Read the rest of this entry »

, , ,

Ado.net 介绍:SqlConnection类的方法
继上一篇Ado.net 介绍:SqlConnection类的属性后再总结下SqlConnection类的方法。共12个。

1:BeginTransaction方法
此方法在连接上开始一个新的事务,返回新的SqlTransaction对象

  1. SqlTransaction btn = conn.BeginTransaction();
  2. 等价于
  3. SqlTransaction btn = new SqlTransaction();
  4. btn.Connection = conn;
  5. btn.Begin();

2:ChangDatebase方法
更新正在进行通信的数据库

  1. SqlConnection conn = new SqlConnection(strconn);
  2. conn.Open();
  3. conn.ChangDatabase("Northwind");
  4. 等价于
  5. SqlConnection conn = new SqlConnection(strconn);
  6. conn.Open();
  7. SqlCommand cmd = conn.CreateCommand();
  8. cmd.CommandText = "USE pubs";
  9. cmd.ExecuteNoQuery();

3/4:ClearPoll和ClearAllpools方法
这两个用来清除连接池的。前者清除单个。后者清队所有。

  1. SqlConnection.ClearPoll();
  2. SqlConnection.ClearAllpools();

Read the rest of this entry »

, , ,

Ado.net 介绍:SqlConnection类的属性
Ado.net 2.0中SqlConnection类共拥有10属性12方法2事件。此篇介绍下SqlConnection类的属性

1:ConnectionString
String/控制SqlConnection对象如何连接到数据源

2:ConnectionTimeout
Int32/SqlConnection对象尝试连接到数据源时等待的时间/秒(只读)

3:Database
String/连接数据库的名称(只读)

4:DataSource
String/连接数据库的位置(只读)即Sql地址

5:FireInfoMessageEventOnUserErrors
Boolean/发生错误时是否激发InfoMessage

6:PacketSize
Int32/与Sql通信时所使用的数据包大小(只读)

7:ServerVersion
String/返回数据源版本(只读)

8:State
ConnectionState/指示Sqlconnection对象当前状态(只读)

9:StatisticsEnabled
Boolean/控制是否为该连接启用统计

10:WorkstationID
String/返回数据库客户端的名称
Read the rest of this entry »

, , ,

Ado.net 介绍:连接字符串生成器-SqlConnectionStringBuilder
使用连接字符串生成器可以方便准确的生成数据库连接字符串。且于防止注入也有一定的益处。
采用SqlConnectionStringBuilder来生成连接字符串:
代码:

  1. SqlConnectionStringBuilder sqlbldr = new SqlConnectionStringBuilder();
  2. sqlbldr.DataSource = "CNGOTHIC";
  3. sqlbldr.UserID = "sa";
  4. sqlbldr.Password = "cngothic";
  5. sqlbldr.InitialCatalog = "pubs";
  6. sqlbldr.IntegratedSecurity = true;
  7. Response.Write(sqlbldr.ConnectionString);
  8. SqlConnection conn = new SqlConnection(sqlbldr.ConnectionString);
  9. conn.Open();

此时输出内容为:Data Source=CNGOTHIC;Initial Catalog=pubs;Integrated Security=True;User ID=sa;Password=gothic
即sqlbldr.ConnectionString的内容;
下面再介绍下。如果加载mdf数据文件。
Read the rest of this entry »

, ,