电竞比分网-中国电竞赛事及体育赛事平台

分享

.net使用中sqlcommand的用法

 pitt圖書 2017-07-03

SqlCommand()方法


SqlCommand cmd = new SqlCommand("insert into mynews value ('插入一條新數(shù)據(jù)')", con);   
 Command對(duì)象的構(gòu)造函數(shù)的參數(shù)有兩個(gè),一個(gè)是需要執(zhí)行的SQL語(yǔ)句,另一個(gè)是數(shù)據(jù)庫(kù)連接對(duì)象。創(chuàng)建Command對(duì)象后,就可以執(zhí)行SQL命令,執(zhí)行后完成并關(guān)閉數(shù)據(jù)連接,示例代碼如下所示。
cmd.ExecuteNonQuery(); //執(zhí)行SQL命令
con.Close(); //關(guān)閉連接
 
SqlCommand類的屬性
 
1.CommandText  
 獲取或設(shè)置要對(duì)數(shù)據(jù)源執(zhí)行的Transact—SQL語(yǔ)句或存儲(chǔ)過(guò)程的名稱。
 
2. CommandType  
獲取或設(shè)置一個(gè)值,該值指示如何解釋CommandText屬性。

當(dāng)將 CommandType 屬性設(shè)置為 StoredProcedure 時(shí),應(yīng)將 CommandText 屬性設(shè)置為存儲(chǔ)過(guò)程的名稱。當(dāng)調(diào)用 Execute 方法之一時(shí),該命令將執(zhí)行此存儲(chǔ)過(guò)程。

用于 SQL Server 的 Microsoft .NET Framework 數(shù)據(jù)提供程序不支持在向通過(guò) TextCommandType 調(diào)用的 SQL 語(yǔ)句或存儲(chǔ)過(guò)程傳遞參數(shù)時(shí)使用問(wèn)號(hào) (?) 占位符。在這種情況下,必須使用命名的參數(shù)。例如:

SELECT * FROM Customers WHERE CustomerID = @CustomerID

 

下面的示例創(chuàng)建一個(gè)SqlCommand并設(shè)置它的一些屬性。

  1. public void CreateSqlCommand()  
  2. {  
  3.           SqlCommand command = new SqlCommand();  
  4.           command.CommandTimeout = 15;  
  5.           command.CommandType = CommandType.Text;  
  6. }  

 
3.Connection 
獲取或設(shè)置SqlCommand的實(shí)例使用的SqlConnection。
 
4.CommandTimeOut   
獲取或設(shè)置在終止執(zhí)行命令的嘗試并生成錯(cuò)誤之前的等待時(shí)間。

 

 

SqlCommand類的方法
 
1.ExecuteNonQuery();  
 它的返回值類型為int型。多用于執(zhí)行增加,刪除,修改數(shù)據(jù)。返回受影響的行數(shù)。當(dāng)select操作時(shí),返回-1。
 
2.ExecuteReader();  
  它的返回類型為SqlDataReader。此方法用于用戶進(jìn)行的查詢操作。使用SqlDataReader對(duì)象的Read();方法進(jìn)行逐行讀取。
例如:

  1. SqlCommand comm =new SqlCommand("select * from CGSZ where cid="+id,conn);    
  2. SqlDataReader reder=comm.ExecuteReader();   
  3. while(reder.Read())   
  4. {    
  5.           //讀出內(nèi)容列  
  6.           string str=reder["cname"].ToString();   
  7.          //讀取分類列  
  8.          string str1=reder["ckind"].ToString();   
  9.           //分別為文本框加載數(shù)據(jù)  
  10.          this.txtContent.Text = str;    
  11.          this.txtClass.Text = str1;     
  12. }  
  1. /// <summary>  
  2. /// 對(duì)連接執(zhí)行 Transact-SQL 語(yǔ)句返回一個(gè)SqlDataReader,查詢是否存在記錄(注意要關(guān)閉)。  
  3. /// </summary>  
  4. /// <param name="sql"></param>  
  5. /// <returns></returns>  
  6. public static SqlDataReader GetReader(string sql)  
  7. {  
  8.     using (SqlConnection con = new SqlConnection(ConnectionString))  
  9.     {  
  10.         SqlCommand cmd = new SqlCommand(sql,con);  
  11.         con.Open();  
  12.         SqlDataReader reader = cmd.ExecuteReader();  
  13.         return reader;  
  14.     }  
  15. }  

其中的讀取數(shù)據(jù)列的時(shí)候。除了使用reder["列名"].ToString();還可以使用reder[索引].ToSting();<注意:這里的索引指的是數(shù)據(jù)庫(kù)中列的索引。從0開(kāi)始。> 

 

3.ExecuteScaler();  
 它的返回值類型多位int類型。它返回的多為執(zhí)行select查詢。得到的返回結(jié)果為一個(gè)值的情況,比如使用count函數(shù)求表中記錄個(gè)數(shù)或者使用sum函數(shù)求和等。

  1. /// <summary>  
  2. /// Update(// || p.Value.ToString().Trim() == "System.Byte[]")) by richmen 2011 05  
  3. /// 注釋掉才可以實(shí)現(xiàn)相片的修改跟保存功能  
  4. /// 執(zhí)行查詢,并返回查詢所返回的結(jié)果集中第一行的第一列。忽略其他列或行。  
  5. /// </summary>  
  6. /// <param name="sql">sql語(yǔ)句或者存儲(chǔ)過(guò)程的名稱</param>  
  7. /// <param name="parameters">null的時(shí)候?yàn)閟ql</param>  
  8. /// <returns></returns>  
  9. public static object ExecuteScalar(string sql, SqlParameter[] parameters)  
  10. {  
  11.     if (parameters != null)  
  12.     {  
  13.         foreach (SqlParameter p in parameters)  
  14.         {  
  15.             if (p.Value == null)// || p.Value.ToString().Trim() == "System.Byte[]")  
  16.                 p.Value = DBNull.Value;  
  17.         }  
  18.     }  
  19.     using (SqlConnection con = new SqlConnection(ConnectionString))  
  20.     {  
  21.         SqlCommand cmd = new SqlCommand();  
  22.         cmd.Connection = con;  
  23.         if (parameters != null)  
  24.         {  
  25.             cmd.CommandType = CommandType.StoredProcedure;  
  26.             cmd.Parameters.AddRange(parameters);  
  27.         }  
  28.         else  
  29.         {  
  30.             cmd.CommandType = CommandType.Text;  
  31.         }  
  32.         cmd.CommandText = sql;  
  33.         try  
  34.         {  
  35.             con.Open();  
  36.             return cmd.ExecuteScalar();  
  37.         }  
  38.         catch  
  39.         {  
  40.             return string.Empty;  
  41.         }  
  42.     }  
  43. }  
  44. }  

4.其它;  
當(dāng)參數(shù)中含有問(wèn)號(hào) (?) 等占位符時(shí),必須使用命名的參數(shù)。

下面的示例演示如何創(chuàng)建 SqlCommand 和向 SqlParameterCollection 中添加參數(shù)。例如:

  1. private static void PrepareCommand(SqlCommand cmd, SqlConnection conn, SqlTransaction trans, string cmdText, SqlParameter[] cmdParms)  
  2.         {  
  3.             if (conn.State != ConnectionState.Open)  
  4.             {  
  5.                 conn.Open();  
  6.             }  
  7.             cmd.Connection = conn;  
  8.             cmd.CommandText = cmdText;  
  9.             if (trans != null)  
  10.             {  
  11.                 cmd.Transaction = trans;  
  12.             }  
  13.             cmd.CommandType = CommandType.Text;  
  14.             if (cmdParms != null)  
  15.             {  
  16.                 for (int i = 0; i < cmdParms.Length; i++)  
  17.                 {  
  18.                     SqlParameter sqlParameter = cmdParms[i];  
  19.                     if ((sqlParameter.Direction == ParameterDirection.InputOutput || sqlParameter.Direction == ParameterDirection.Input) && sqlParameter.Value == null)  
  20.                     {  
  21.                         sqlParameter.Value = DBNull.Value;  
  22.                     }  
  23.                     cmd.Parameters.Add(sqlParameter);  
  24.                 }  
  25.             }  
  26.         }  
  1. private static void UpdateDemographics(Int32 customerID,string demoXml, string connectionString)  
  2. {  
  3.     // Update the demographics for a store, which is stored   
  4.     // in an xml column.   
  5.     string commandText = "UPDATE Sales.Store SET Demographics = @demographics "  
  6.         + "WHERE CustomerID = @ID;";  
  7.   
  8.     using (SqlConnection connection = new SqlConnection(connectionString))  
  9.     {  
  10.         SqlCommand command = new SqlCommand(commandText, connection);  
  11.         command.Parameters.Add("@ID", SqlDbType.Int);  
  12.         command.Parameters["@ID"].Value = customerID;  
  13.   
  14.         // Use AddWithValue to assign Demographics.  
  15.         // SQL Server will implicitly convert strings into XML.  
  16.         command.Parameters.AddWithValue("@demographics", demoXml);  
  17.   
  18.         try  
  19.         {  
  20.             connection.Open();  
  21.             Int32 rowsAffected = command.ExecuteNonQuery();  
  22.             Console.WriteLine("RowsAffected: {0}", rowsAffected);  
  23.         }  
  24.         catch (Exception ex)  
  25.         {  
  26.             Console.WriteLine(ex.Message);  
  27.         }  
  28.     }  
  29. }  


    本站是提供個(gè)人知識(shí)管理的網(wǎng)絡(luò)存儲(chǔ)空間,所有內(nèi)容均由用戶發(fā)布,不代表本站觀點(diǎn)。請(qǐng)注意甄別內(nèi)容中的聯(lián)系方式、誘導(dǎo)購(gòu)買等信息,謹(jǐn)防詐騙。如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請(qǐng)點(diǎn)擊一鍵舉報(bào)。
    轉(zhuǎn)藏 分享 獻(xiàn)花(0

    0條評(píng)論

    發(fā)表

    請(qǐng)遵守用戶 評(píng)論公約

    類似文章 更多