數據庫操做集錦

下面是數據庫操做集錦,使用前先添加命名空間using System.Data.SqlClient;sql

/// <summary>
        /// 還回DataTable類型
        /// </summary>
        /// <param name="sql">SQL語句</param>
        /// <returns></returns>
        public static DataTable ExcuteSQL(string sql)
        {
            DataTable dt = null;
            string connstring="server=localhost;database=DataBase;Uid=username;pwd=userpass";
            using (SqlConnection sqlconn = new SqlConnection(connstring))
            {
                sqlconn.Open();
                SqlCommand slcom = sqlconn.CreateCommand();
                slcom.CommandText = sql;
                SqlDataAdapter adap = new SqlDataAdapter(slcom);
                adap.Fill(dt);
                sqlconn.Close();
            }
            return dt;
        }
        /// <summary>
        /// 返回Object類型
        /// </summary>
        /// <param name="sql">SQL語句</param>
        /// <returns></returns>
        public static Object ExcuteSQLScalar(string sql)
        {
            Object ob = null;
            string connstring="server=localhost;database=DataBase;Uid=username;pwd=userpass";
            using (SqlConnection sqlconn = new SqlConnection(connstring))
            {
                sqlconn.Open();
                SqlCommand slcom = sqlconn.CreateCommand();
                slcom.CommandText = sql;
                ob = slcom.ExecuteScalar();
                sqlconn.Close();
            }
            return ob;
        }
        /// <summary>
        /// 不返回任何值
        /// </summary>
        /// <param name="sql">SQL語句</param>
        public static void SQLExcuteNone(string sql)
        {
            string connstring="server=localhost;database=DataBase;Uid=username;pwd=userpass";
            using (SqlConnection sqlconn = new SqlConnection(connstring))
            {
                sqlconn.Open();
                SqlCommand slcom = sqlconn.CreateCommand();
                slcom.CommandText = sql;
                slcom.ExecuteNonQuery();
                sqlconn.Close();
            }
        }
View Code
相關文章
相關標籤/搜索