using System;
Using System.Collections.Generic;
Using System.Linq;
Using System.Text;
Using System.Data;
Using System.Data.SqlClient;
Using System.Windows.Forms;
1 Public classDBHelper2 {3 Static stringConnStr ="Workstation id = localhost;"+4 "Integrated Security = SSPI;"+5 "database = DB name;";//Fill in the login information of the SQL database. 6 7 8 StaticSqlConnection conn =NewSqlConnection (CONNSTR);9 Ten Public StaticSqlDataReader Getdatareader (stringsql//The return value is an array that can be used by dr[0],dr[1] to use the values of each field One { ASqlConnection myconn =Conn; -SqlDataReader dr =NULL; - the Try - { - if(Myconn.state = =connectionstate.closed) - { + MyConn.Open (); - } +SqlCommand cmd =NewSqlCommand (SQL, myconn); A atDr =cmd. ExecuteReader (commandbehavior.closeconnection); - } - Catch - { - - if(Myconn.state = =ConnectionState.Open) in { - myconn.close (); to } + - } the returnDr; * } $ Panax Notoginseng Public Static BOOLExecuteNonQuery (stringsql//for UPDATE, INSERT, and DELETE statements, the return value is the number of rows affected by the command. for all other types of statements, the return value is-1. If a rollback occurs, the return value is also-1 - { the intn =0; + A Try the { + if(Conn. state = =connectionstate.closed) - { $ Conn. Open (); $ } -SqlCommand cmd =NewSqlCommand (SQL, conn); -n =cmd. ExecuteNonQuery (); the - }Wuyi Catch the { - Wu return false; - } About finally $ { - if(Conn. state = =ConnectionState.Open) - { - Conn. Close (); A } + } the returnn >0; - } $ the Public StaticObject ExecuteScalar (stringsql//use ExecuteScalar (), additions and deletions if successful, an object is returned, or a null is returned; the { theObject OB =NULL; the - Try in { the if(Conn. state = =connectionstate.closed) the { About Conn. Open (); the } theSqlCommand cmd =NewSqlCommand (SQL, conn); theOB =cmd. ExecuteScalar (); + } - Catch the {Bayi return NULL; the } the finally - { - if(Conn. state = =ConnectionState.Open) the { the Conn. Close (); the } the } - returnob; the } the } the}
C#_dbhelper_sql the database operation class.