C # _ DBHelper_ SQL database operation class .,
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 class DBHelper 2 {3 static string connStr = "Workstation id = localhost;" + 4 "Integrated Security = SSPI;" + 5 "Database = Database name ;"; // enter the logon information of the SQL database. 6 7 8 static SqlConnection conn = new SqlConnection (connStr); 9 10 public static SqlDataReader GetDataReader (string SQL) // The returned value is an array. You can use dr [0], dr [1] uses the values of each field 11 {12 SqlConnection myConn = conn; 13 SqlDataReader dr = null; 14 15 try16 {17 if (myConn. state = ConnectionState. closed) 18 {19 myConn. open (); 20} 21 SqlCommand cmd = new SqlCommand (SQL, myConn); 22 23 dr = cmd. executeReader (CommandBehavior. closeConn Ection); 24} 25 catch 26 {27 28 if (myConn. state = ConnectionState. open) 29 {30 myConn. close (); 31} 32 33} 34 return dr; 35} 36 37 public static bool ExecuteNonQuery (string SQL) // for UPDATE, INSERT, and DELETE statements, the returned 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 returned value is-138 {39 int n = 0; 40 41 try42 {43 if (conn. state = ConnectionState. closed) 44 {45 conn. open (); 46} 47 SqlCommand cmd = new SqlCommand (SQL, conn); 48 n = cmd. executeNonQuery (); 49 50} 51 catch52 {53 54 return false; 55} 56 finally57 {58 if (conn. state = ConnectionState. open) 59 {60 conn. close (); 61} 62} 63 return n> 0; 64} 65 66 public static Object ExecuteScalar (string SQL) // use ExecuteScalar (). If addition, deletion, modification, and query are successful, an Object is returned. Otherwise, a null value is returned. 67 {68 Object ob = null; 69 70 try71 {72 if (conn. state = ConnectionState. closed) 73 {74 conn. open (); 75} 76 SqlCommand cmd = new SqlCommand (SQL, conn); 77 ob = cmd. executeScalar (); 78} 79 catch80 {81 return null; 82} 83 finally84 {85 if (conn. state = ConnectionState. open) 86 {87 conn. close (); 88} 89} 90 return ob; 91} 92} 93}