Ado.net 介绍:使用参数化查询
以get方式传递参数.后获取参数当作条件合并到SQL语句中.查询想要的数据.
URL表现形式:http://www.cngothic.com/search.aspx?customerid=TOMSP
代码如下:
- SqlConnection conn = new SqlConnection();
- conn.ConnectionString = ConfigurationManager.ConnectionStrings["strcon"].ConnectionString;
- conn.Open();
- //打开数据库
- string SqlStr;
- SqlStr = "SELECT OrderID,CustomerID,OrderDate,EmployeeID FROM Orders WHERE CustomerID=@CustomerID";
- //带参数的SQL语句
- SqlCommand SqlCmd = new SqlCommand(SqlStr, conn);
- SqlCmd.Parameters.AddWithValue"("@CustomerID", TOMSP");
- //在customerid参数没有值的情况下为其赋个值为:TOMSP
- SqlDataReader redr = SqlCmd.ExecuteReader();
- while (redr.Read())
- {
- Response.Write(redr["OrderID"] + "<br />");
- Response.Write(Request.QueryString["CustomerID"]);
- }
Read the rest of this entry »
AddWithValue, Ado.net, Ado.net 介绍, 使用参数化查询
Ado.net 介绍:SqlConnection类的方法
继上一篇Ado.net 介绍:SqlConnection类的属性后再总结下SqlConnection类的方法。共12个。
1:BeginTransaction方法
此方法在连接上开始一个新的事务,返回新的SqlTransaction对象
- SqlTransaction btn = conn.BeginTransaction();
- 等价于
- SqlTransaction btn = new SqlTransaction();
- btn.Connection = conn;
- btn.Begin();
2:ChangDatebase方法
更新正在进行通信的数据库
- SqlConnection conn = new SqlConnection(strconn);
- conn.Open();
- conn.ChangDatabase("Northwind");
- 等价于
- SqlConnection conn = new SqlConnection(strconn);
- conn.Open();
- SqlCommand cmd = conn.CreateCommand();
- cmd.CommandText = "USE pubs";
- cmd.ExecuteNoQuery();
3/4:ClearPoll和ClearAllpools方法
这两个用来清除连接池的。前者清除单个。后者清队所有。
- SqlConnection.ClearPoll();
- SqlConnection.ClearAllpools();
Read the rest of this entry »
Ado.net, Ado.net 介绍, SqlConnection, 方法
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, Ado.net 介绍, SqlConnection, 属性
Ado.net 介绍:连接字符串生成器-SqlConnectionStringBuilder
使用连接字符串生成器可以方便准确的生成数据库连接字符串。且于防止注入也有一定的益处。
采用SqlConnectionStringBuilder来生成连接字符串:
代码:
- SqlConnectionStringBuilder sqlbldr = new SqlConnectionStringBuilder();
- sqlbldr.DataSource = "CNGOTHIC";
- sqlbldr.UserID = "sa";
- sqlbldr.Password = "cngothic";
- sqlbldr.InitialCatalog = "pubs";
- sqlbldr.IntegratedSecurity = true;
- Response.Write(sqlbldr.ConnectionString);
- SqlConnection conn = new SqlConnection(sqlbldr.ConnectionString);
- 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 »
Ado.net, Ado.net 介绍, SqlConnectionStringBuilder