首先要在類中引入

using System.Data.SqlClient;
using System.Data;

要返回的操作

SqlConnection conn = new SqlConnection(strConn);
                conn.Open(); //打開連接

 SqlDataAdapter adpGetDst = new SqlDataAdapter(strSql, conn);
            DataSet dstReturn = new DataSet();
            SqlCommandBuilder cbdGetDst = new SqlCommandBuilder(adpGetDst);
            adpGetDst.Fill(dstReturn);//查詢的結果放放DateSet中
            return dstReturn;

           conn.Close();//操作完成後關閉連接

 不用返回的操作

           SqlCommand myCmd = new SqlCommand();

          if (conn.State == ConnectionState.Closed)//判斷當前狀態是否關閉
            {
                conn.Open();
            }

            myCmd.Connection = conn;
            myCmd.CommandType = CommandType.Text;
            myCmd.CommandTimeout = 120;
            myCmd.CommandText = SqlStr;
            return myCmd.ExecuteNonQuery();

           conn.Close();

執行無返回的存儲過程

        int intflag;
        bool bolexeProcedure = false;
        SqlCommand myCmd = new SqlCommand();
        try
        {
            if (conn.State == ConnectionState.Closed)
            {
                conn.Open();
            }

            myCmd.Connection = conn;
            myCmd.CommandType = CommandType.StoredProcedure;
            myCmd.Parameters.AddRange(sqlParaArray);
            myCmd.CommandTimeout = 120;
            myCmd.CommandText = SqlStr;
            intflag=myCmd.ExecuteNonQuery();
            if (intflag != -1)//如執行成功則反回非-1的值,如有返回值則返回的結果是返回值
            {
                bolexeProcedure = true;
            }

sqlParaArray是傳入的參數寫法為

 SqlParameter[] sqlParaArray = new SqlParameter[IntParamterLen];
 sqlParaArray[i] = new SqlParameter(參數名稱, 參數值);//i表示輸入數的順序

批處理寫法

SqlCommand myCmd = new SqlCommand();
        try
        {
            if (conn.State == ConnectionState.Closed)
            {
                conn.Open();
            }
            myCmd.Connection = conn;
            myCmd.CommandType = CommandType.Text;
            myCmd.CommandTimeout = 120;
            myCmd.CommandText = SqlStr;
            myCmd.Parameters.AddRange(Parameters);

            return myCmd.ExecuteNonQuery();
        }

任何調用數據邊接的在使用完成後都要進行Close操作

posted on 2008-11-26 11:50  Blade  阅读(368)  评论(0编辑  收藏  举报