close

.Net 與資料庫溝通

Sample Code:

        //開啟連線
        public static SqlConnection OpenSqlConn(string Server, string Database, string dbuid, string dbpwd)
        {
            string cnstr = string.Format("server={0};database={1};uid={2};pwd={3};Connect Timeout = 180", Server, Database, dbuid, dbpwd);
            SqlConnection icn = new SqlConnection();
            icn.ConnectionString = cnstr;
            if (icn.State == ConnectionState.Open) icn.Close();
            icn.Open();
            return icn;
        }

        //查詢

        public static DataTable GetSqlDataTable(string Server, string Database, string dbuid, string dbpwd, string SqlString)
        {
            DataTable myDataTable = new DataTable();
            SqlConnection icn = null;
            icn = OpenSqlConn(Server, Database, dbuid, dbpwd);
            SqlCommand isc = new SqlCommand();
            SqlDataAdapter da = new SqlDataAdapter(isc);
            isc.Connection = icn;
            isc.CommandText = SqlString;
            isc.CommandTimeout = 600;
            DataSet ds = new DataSet();
            ds.Clear();
            da.Fill(ds);
            myDataTable = ds.Tables[0];
            if (icn.State == ConnectionState.Open) icn.Close();
            return myDataTable;
        }

        //新增,刪除,修改

        public static void SqlInsertUpdateDelete(string Server, string Database, string dbuid, string dbpwd, string SqlSelectString)
        {
            SqlConnection icn = OpenSqlConn(Server, Database, dbuid, dbpwd);
            SqlCommand cmd = new SqlCommand(SqlSelectString, icn);
            SqlTransaction mySqlTransaction = icn.BeginTransaction();
            try
            {
                cmd.Transaction = mySqlTransaction;
                cmd.ExecuteNonQuery();
                mySqlTransaction.Commit();
            }
            catch (Exception ex)
            {
                mySqlTransaction.Rollback();
                throw (ex);
            }
            if (icn.State == ConnectionState.Open) icn.Close();
        }

arrow
arrow
    全站熱搜

    sendohlun 發表在 痞客邦 留言(0) 人氣()