SqlCommand 這個對象可以讓我們在數據庫上做一下操作,比如說增、刪、改、查。都可以使用SqlCommand 這個對象。
首先,要使用SqlCommand 對象的話,必須先聲明它。
SqlCommand cmd = new SqlCommand(strSQL, conn);
其中strSQL 是我們定義好的SQL 語句,conn 是聲明好的數據庫鏈接。
我們來看一下如果需要在數據庫中插入一條數據應該怎么操作,也就是insert。
一般的可以用ExecuteNonQuery() 方法;ExecuteNonQuery() 方法還可以執行修改、刪除語句。
string strSQL = @"intsert into tb_users (id,username,password ) values ('1','system','123456')";
SqlCommand cmd = new SqlCommand(strSQL , conn);
int i = Convert.ToInt32(cmd.ExecuteNonQuery());
ExecuteNonQuery() 方法執行update 語句。
string strSQL= @"update tb_users set password='654321' where username='system'"; SqlCommand cmd = new SqlCommand(strSQL); cmd.Connection = conn; int i = Convert.ToInt32(cmd.ExecuteNonQuery());
ExecuteNonQuery() 方法執行delete 語句。
string strSQL= @"delete from tb_users where username='system'"; SqlCommand cmd = new SqlCommand(strSQL); cmd.Connection = conn; int i = Convert.ToInt32(cmd.ExecuteNonQuery());
然后就是最常用的select 查詢語句,
ExecuteReader()方法可以執行查找語句,它返回的是一個結果集,一般的我們可以用一個叫做SqlDataReader的對象來接收這個結果集,比如說想要查找所有的users ,下面的語句執行后,在data里面就得到了所有的tb_users 表里的信息了。
SqlCommand cmd = new SqlCommand("select * from tb_users", conn); SqlDataReader data= cmd.ExecuteReader();
還有就是ExecuteScalar() 方法,它返回一個單一的結果,比如說上一篇文章中就用到的是這個方法。
string sqlStr = "SELECT count(1) FROM tb_Users WHERE username='" + username +"' and password='"+password+"' "; Console.WriteLine(sqlStr); conn = new SqlConnection(strSQLconn); conn.Open(); SqlCommand comm = new SqlCommand(sqlStr,conn); int i = Convert.ToInt32(comm.ExecuteScalar().ToString()); if(i>=1) { conn.Close(); return true; } conn.Close(); return false;