SqlConnection
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using System.Data.Common;
namespace SqlConn
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//建立數據源鏈接
SqlConnection nwind_conn = new SqlConnection();
nwind_conn.ConnectionString = "server=localhost;database=Bookstore;uid=sa;pwd=sa; Connection Timeout=15; Packet Size=8192;Persist Security Info=true;";
//建立數據讀取
SqlCommand nwind_comm = new SqlCommand();
nwind_comm.Connection = nwind_conn;
nwind_comm.CommandText = "SELECT book_name from book_info";
nwind_comm.CommandTimeout = 25;
nwind_comm.CommandType = CommandType.Text;
//打開數據源鏈接
nwind_conn.Open();
//建立事務,要建立事務須先打開和數據庫的鏈接
SqlTransaction Tran;
Tran = nwind_conn.BeginTransaction();
nwind_comm.Transaction = Tran;
//結束并提交事務,應在數據讀取前(即沒有執行ExecuteNonQuery,ExecuteReader,ExecuteScalar,ExecuteXmlReader)前結束事務
Tran.Commit();
//或:Tran.Rollback();
//執行數據讀取
SqlDataReader reader = nwind_comm.ExecuteReader();
//嘗試取消命令的執行,如果嘗試失敗不會產生異常
nwind_comm.Cancel();
//關閉數據源鏈接
nwind_conn.Close();
}
}
}