The content is not complete and will be added later.
C # links to SQL.
1. Link string configuration information is saved in app. Config
<!--connect the database string --<connectionStrings> <add name= "Dbstrconn" connectionstring= "Data source=.; Initial catalog= database; User id= username; password= password "/> </connectionStrings>
2. Add System.Configuration Reference
3. Get the link string in DBHelper
/* * Get Connection Database String * This string exists in the App. Config app configuration file */private static string strconnection = Configurationmanager.connectionstrings ["Dbstrconn"]. ConnectionString; Dbstrconn is the "name" name in app. Config
4.
1) ExecuteNonQuery method performs insert, modify, delete
public static int toinupdel_executenonquery (String sql) { //connection command using (SqlConnection conn = new SqlConnection ( strconnection)) { Conn. Open (); Open the connection using (SqlCommand cmd = conn. CreateCommand ()) { //Execute SQL statement cmd.commandtext = SQL; Returns the number of rows affected by the return cmd. ExecuteNonQuery (); }
2) ExecuteScalar Method execution Query
public static int toselect_executescalar (String sql) { using (SqlConnection conn = new SqlConnection (strconnection) ) { Conn. Open (); using (SqlCommand cmd = conn. CreateCommand ()) { cmd.commandtext = SQL; Returns the result return (int) cmd. ExecuteScalar ();}}}
3) The DataTable is used to query the result less than the SQL
public static DataTable executedatatable (String sql) { using (SqlConnection conn = new SqlConnection (strconnection)) { Conn. Open (); using (SqlCommand cmd = conn. CreateCommand ()) { cmd.commandtext = SQL; SqlDataAdapter adapter = new SqlDataAdapter (cmd); DataSet DataSet = new DataSet (); Adapter. Fill (dataset); return DataSet. Tables[0]; } } }
4) SqlDataReader need to be closed manually
public static SqlDataReader ExecuteReader (String sql) { SqlConnection conn = new SqlConnection (strconnection); SqlCommand cmd = new SqlCommand (sql,conn); Try {Conn. Open (); SqlDataReader reader = cmd. ExecuteReader (commandbehavior.closeconnection); CommandBehavior.CloseConnection automatically closes the connection return reader when the DataReader is closed; } catch (SqlException ex) {throw ex; }}
What is wrong welcome to point out or have any suggestions also line, we learn together.
Encapsulated DBHelper (C #)