The primary role of this class is to simplify the work when connecting to SQL Server databases
<?xml version="1.0" encoding="utf-8" ?>< configuration> <connectionStrings> <add name="sqlcon" connectionstring="Data source=.;i Nitial Catalog=mydb; User Id=sa; password=123456"/> </connectionStrings></configuration>
App. Config configuration file
using System.Configuration; using System.Data.SqlClient; using System.Data; In "References" you need to add System.Configuration
classSqlHelper {Private Static stringConnStr = configurationmanager.connectionstrings["Sqlcon"]. ConnectionString; //use variable length parameters to simplify Public Static intExecuteNonQuery (stringSqlparamssqlparameter[] Parameters) { using(SqlConnection conn =NewSqlConnection (CONNSTR)) {Conn. Open (); using(SqlCommand cmd =Conn. CreateCommand ()) {Cmd.commandtext=SQL; //foreach (SqlParameter param in parameters)//{ //cmd. Parameters.Add (param); //}cmd. Parameters.addrange (Parameters); returncmd. ExecuteNonQuery (); } } } Public Static ObjectExecuteScalar (stringSqlparamssqlparameter[] Parameters) { using(SqlConnection conn =NewSqlConnection (CONNSTR)) {Conn. Open (); using(SqlCommand cmd =Conn. CreateCommand ()) {Cmd.commandtext=SQL; Cmd. Parameters.addrange (Parameters); returncmd. ExecuteScalar (); } } } //only used to execute less query results than SQL, the query results are stored locally Public StaticDataTable executedatatable (stringSqlparamssqlparameter[] Parameters) { using(SqlConnection conn =NewSqlConnection (CONNSTR)) {Conn. Open (); using(SqlCommand cmd =Conn. CreateCommand ()) {Cmd.commandtext=SQL; Cmd. Parameters.addrange (Parameters); SqlDataAdapter Adapter=NewSqlDataAdapter (CMD); DataSet DataSet=NewDataSet (); Adapter. Fill (DataSet); returnDataSet. tables[0]; } } } }
The functions implemented are:
1. The function of the ExecuteNonQuery method: Execute SQL statements, for example: UPDATE, INSERT, query
2. The function of the ExecuteScalar method is to return only one data, for example, get count (*), or Max (), and for the data of the extra result, only the data of the first column of the first row will be returned.
3, the function of Executedatatable method is: Return the data that needs to be queried back to a tatatable, convenient local operation of data
Note: SqlParameter parameterized queries to prevent SQL injection vulnerabilities
C # Connection Sqlseveral class SqlHelper