Class DBHelper {//public static string connstr = "server=.; database=superktv;uid=sa;pwd=123456 "; public static string connstr = "server=.; database=dormitory;uid=sa;pwd=123456 "; Database link object private static SqlConnection Conn = null; Initialize database link private static void Initconnection () {//If the connection object does not exist, create a connection if (Conn = = null) Conn = new SqlConnection (CONNSTR); If the connection object is closed, open the connection if (conn.state = = connectionstate.closed) Conn.Open (); If the connection is interrupted, restart the connection if (conn.state = = Connectionstate.broken) {conn.close (); Conn.Open (); }}//query, get DataReader public static SqlDataReader Getdatareader (string sqlstr) {in Itconnection (); SqlCommand cmd = new SqlCommand (sqlstr, Conn); commandbehavior.closeconnection command behavior: Automatically closes the occupied Connection object when the DataReader object is closed returnCmd. ExecuteReader (commandbehavior.closeconnection); }//Query, get DataTable public static DataTable Getdatatable (String sqlstr) {initconnection (); DataTable table = new DataTable (); SqlDataAdapter dap = new SqlDataAdapter (Sqlstr, Conn); Dap. Fill (table); Conn.close (); return table; }//query, get DataSet public static DataSet GetDataSet (String sqlstr) {initconnection (); DataSet ds = new DataSet (); SqlDataAdapter dap = new SqlDataAdapter (Sqlstr, Conn); Dap. Fill (DS); Conn.close (); return DS; }//Add change to delete public static bool ExecuteNonQuery (string sqlstr) {initconnection (); SqlCommand cmd = new SqlCommand (sqlstr, Conn); int result = cmd. ExecuteNonQuery (); Conn.close (); return result > 0; }//execute aggregate function public static oBject executescalar (String sqlstr) {initconnection (); SqlCommand cmd = new SqlCommand (sqlstr, Conn); Object result = cmd. ExecuteScalar (); Conn.close (); return result; } }
C # DBHelper Class