標籤:style blog http io color os ar 使用 for
綜合樣本
說明:前面介紹了那麼多,光說不練假把式,還是做個執行個體吧。
表:首先你要準備一張表,這個自己準備吧。我們以學生表為例。
1、ExecuteScalar方法
ExecuteScalar方法執行返回單個值的命令。例如,如果想擷取Student資料庫中表studentInfo的學生的總人數,則可以使用這個方法執行SQL查詢:
Select count(*) from studentInfo .
(1) 建立Windows Application 應用程式
(2) 在Form1上添加一個按鈕Button控制項和一個標Label簽控制項
(3) 雙擊按鈕,自動進入代碼編輯介面
首先添加命名空間: using System.Data.SqlClient;
(4)編寫按鈕的Click事件的處理事件代碼:
using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Text;using System.Windows.Forms;using System.Data.SqlClient;namespace DataBase{ public partial class Form1 : Form{public Form1(){ InitializeComponent();}private void button1_Click(object sender, EventArgs e){ try { //定義命令文本 string commandText = "select count(*) from studentInfo"; //定義連接字串 string connString="server=(local);Initial Catalog=Student;Integrated Security=SSPI;"; //string connString= "server=(local);user id=sa;Initial Catalog=Student;pwd=;"; //定義Connection對象 SqlConnection conn = new SqlConnection(); //設定Connection對象的ConnectionString屬性 conn.ConnectionString = connString; //建立Command對象,此時conn對象並不需要開啟串連 SqlCommand cmd = new SqlCommand(commandText, conn); //開啟串連 conn.Open(); //執行命令,返回結果 string count = cmd.ExecuteScalar().ToString(); //記得關閉串連 conn.Close(); this.label1.Text = "共有" + count + "位學生!";}catch (Exception ex){ MessageBox.Show("資料庫連接失敗" + ex.Message);} } }}
執行結果介面
分析代碼:
第1步是引入命名空間:System.Data.SqlClient,表示將使用SQL Server.NET 資料提供者: using System.Data.SqlClient;
第2步是 按鈕button1_Click單擊事件中首先建立立了串連並設定了其連接字串屬性:
string connString="server=(local);Initial Catalog=Student;Integrated Security=SSPI;";
//string connString= "server=(local);user id=sa;Initial Catalog=Student;pwd=;";
//定義Connection對象
SqlConnection conn = new SqlConnection();
//設定Connection對象的ConnectionString屬性
conn.ConnectionString = connString;
第三步,建立Command 對象,並將命名文本和連線物件傳遞給其建構函式:
SqlCommand cmd = new SqlCommand(commandText, conn);
其中,commandText為最初定義的命名文本:
string commandText = "select count(*) from studentInfo";
此時conn對象沒有開啟,因為這不是必須的。
第四步 現在需要執行操作了,所以首先要開啟串連,然後執行操作:
conn.Open();
string count = cmd.ExecuteScalar().ToString();
由於ExecuteScalar()方法傳回型別為object,因此使用了ToString()方法將其轉換為string以後賦值給count。
注意:一般使用ExecuteScalar()方法時都必須用到類型轉換。
第五步資料庫訪問完畢以後應該立即關閉串連,這是一個好習慣:
corm.Close();
第六步最後將讀取的資訊通過label1顯示出來:
this.label1.Text="共有"+count+"位學生!";
上面的代碼中並沒有指定Command對象的CommandType屬性,這時CommandType的值將為預設的Text,當然也可以通過如下代碼顯示指定其類型,但這不是必須的。
cmd.CommandType=CommandType.Text;
C#與資料庫訪問技術總結(七)綜合樣本