C#連線SQL Server資料庫(二)
執行SQL語句:Command物件
1.Command物件概述
Command物件是一個數據命令物件,主要功能是向資料庫傳送查詢、更新、刪除、修改操作的SQL語句。Command物件主要有以下幾種方式。
SqlCommand:用於向SQL Server資料庫傳送SQL語句,位於System.Data.SqlClient名稱空間。
OleDbCommand:用於向使用OLEDB公開的資料庫傳送SQL語句,位於System.Data.OleDb名稱空間。例如,Access資料庫和MySQL資料庫都是OLEDB公開的資料庫。
OdbcCommand:用於向ODBC公開的資料庫傳送SQL語句,位於System.Data.Odbc
OracleCommand:用於向Oracle資料庫傳送SQL語句,位於System.Data.OracleClient名稱空間。
2.設定資料來源型別
Command物件有3個重要的屬性,分別是Connection、CommandText和CommandType。Connection屬性用於設定SqlCommand使用的SqlConnection。CommandText屬性用於設定要對資料來源執行的SQL語句或儲存過程。CommandType屬性用於設定指定CommandText的型別。CommandType屬性的值是CommandType列舉值,CommandType列舉有3個列舉成員,分別介紹如下。
StoredProcedure:儲存過程的名稱。
TableDirect:表的名稱。
Text:SQL文字命令。
如果要設定資料來源的型別,則可以通過設定CommandType屬性來實現。
3.執行SQL語句
Command物件需要取得將要執行的SQL語句,通過呼叫該類提供的多種方法,向資料庫提交SQL語句。下面詳細介紹SqlCommand物件中的幾種執行SQL語句的方法。
1.ExecuteNonQuery方法
執行SQL語句,並返回受影響的行數,在使用SqlCommand向資料庫傳送增、刪、改命令時,通常使用ExecuteNonQuery方法執行傳送的SQL語句。
private void button1_Click(object sender,EventArgs e)
{
string connString = "server=.;database=denglu;uid=test;pwd=test;connect timeout=5";
SqlConnection sqlconn = new SqlConnection(connString);
sqlconn.Open();
SqlCommand sqlcmd = new SqlCommand();
sqlcmd.Connection = sqlconn;
sqlcmd.CommandText = "update Users set password=888 where username='哈哈哈'";
sqlcmd.CommandType = CommandType.Text;
//int i = Convert.ToInt32(sqlcmd.ExecuteNonQuery()); //ExecuteNonQuery返回受影響的行數
//MessageBox.Show(i.ToString());
}
2.ExecuteReader方法
執行SQL語句,並生成一個包含資料的SqlDataReader物件的例項。
程式碼:
private void button1_Click(object sender,EventArgs e)
{
string connString = "server=.;database=denglu;uid=test;pwd=test;connect timeout=5";
SqlConnection sqlconn = new SqlConnection(connString);
sqlconn.Open();
SqlCommand sqlcmd = new SqlCommand();
sqlcmd.Connection = sqlconn;
sqlcmd.CommandText = "select password from users";
sqlcmd.CommandType = CommandType.Text;
//使用ExecuteReader方法例項化一個SqlDataReader物件
SqlDataReader sdr = sqlcmd.ExecuteReader();
while (sdr.Read())
{
listView1.Items.Add(sdr[0].ToString());
}
sqlconn.Dispose();
button1.Enabled = false;
}
介面:
執行SQL語句,返回結果集中的第一行的第一列
程式碼:
SqlConnection sqlConnection;
private void Form2_Load(object sender,EventArgs e)
{
string connString = "server=.;database=TBWRIMS;uid=test;pwd=test;connect timeout=5";
sqlConnection = new SqlConnection(connString);
sqlConnection.Open();
}
private void btn1_Click(object sender,EventArgs e)
{
try
{
if (sqlConnection.State == ConnectionState.Open || txt1.Text != "")
{
SqlCommand sqlCommand = new SqlCommand(); //***
sqlCommand.Connection = sqlConnection; //設定Connection屬性
sqlCommand.CommandText = "select count(*) from" + txt1.Text.Trim(); // 設定CommandText屬性,以及SQL語句
sqlCommand.CommandType = CommandType.Text; //設定CommandType屬性為Text,使其只執行SQL語句
int i = Convert.ToInt32(sqlCommand.ExecuteScalar()); //使用ExecuteScalar方法獲取指定資料表中的資料數量
lab2.Text = "資料表中共有:"+ i.ToString() + "條資料";
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
介面: