ADO.Net之SqlConnection、 Sqlcommand的應用。
ADO.Net之SqlConnection、 Sqlcommand的應用。
知識點:
1.為了能夠使用SQLConnection類,我們首先需要引用命名空間System.Data.SqlClient(using System.Data.SqlClient);接著創建SQLConnection類型的實例對象
mSqlConnection,為其屬性ConnectionString賦值連接字符串;然後調用Open()方法,這就完成了數據庫的連接操作;最後在完成訪問數據操作之後,調用Close()方法,關閉連接。
2.基於連接的對象。它們是數據提供程序對象,如Connection、Command。它們連接到數據庫,執行SQL語句,遍歷只讀結果集或者填充DataSet。基於連接的對象是針對具體數據源類型的,並且可以在提供程序制定的命令空間中(例如SQL Server提供程序的System.Data.SqlClient
一、SqlConnection的應用
連接數據庫,實現簡單的登錄功能,代碼如下:
SqlConnection sqlConnection = new SqlConnection();
sqlConnection.ConnectionString
=
"Server=(local);Database=EduBaseDemo;Integrated
Security=sspi";
SqlCommand
sqlCommand = new SqlCommand();
sqlCommand.Connection
= sqlConnection;
sqlCommand.CommandText
=
"SELECT
COUNT(1) FROM tb_User"
+ " WHERE
No=‘" + this.txt_user.Text.Trim() + "‘"
+ " AND
Password=HASHBYTES(‘MD5‘,‘" + this.txt_pass.Text.Trim() + "‘);";
sqlConnection.Open();
int rowCount =
(int)sqlCommand.ExecuteScalar();
sqlConnection.Close();
if (rowCount ==
1)
{
MessageBox.Show("您好,登錄成功。");
}
else
{
MessageBox.Show("用戶號或密碼錯誤,請重新輸入");
this.txt_pass.Focus();
this.txt_pass.SelectAll();
}
二、SQLCommand的應用
連接數據庫,實現簡單的查詢功能
string connString = "Data Source=(local);Initial Catalog=EduBaseDemo;User
Id=userId;Password=password";
using
(SqlConnection conn = new SqlConnection(connString))
{
conn.Open();
string sql = @"select * from table";
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
cmd.ExecuteNonQuery();
}
conn.Close();
}
ADO.Net之SqlConnection、 Sqlcommand的應用。