数据库操作集锦
下面是数据库操作集锦,使用前先添加命名空间using System.Data.SqlClient;
/// <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(); } }