using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Windows.Forms;
1publicclassDBHelper2{3staticstringconnStr ="Workstation id = localhost;"+4"Integrated Security = SSPI;"+5"Database =数据库名字;";//填入SQL数据库的登录信息。678staticSqlConnection conn =newSqlConnection(connStr);910publicstaticSqlDataReader GetDataReader(stringsql)//返回值是一个数组,可通过dr[0],dr[1]使用各字段的值11{12SqlConnection myConn =conn;13SqlDataReader dr =null;1415try16{17if(myConn.State ==ConnectionState.Closed)18{19myConn.Open();20}21SqlCommand cmd =newSqlCommand(sql, myConn);2223dr =cmd.ExecuteReader(CommandBehavior.CloseConnection);24}25catch26{2728if(myConn.State ==ConnectionState.Open)29{30myConn.Close();31}3233}34returndr;35}3637publicstaticboolExecuteNonQuery(stringsql)//对于 UPDATE、INSERT 和 DELETE 语句,返回值为该命令所影响的行数。对于所有其他类型的语句,返回值为 -1。如果发生回滚,返回值也为 -138{39intn =0;4041try42{43if(conn.State ==ConnectionState.Closed)44{45conn.Open();46}47SqlCommand cmd =newSqlCommand(sql, conn);48n =cmd.ExecuteNonQuery();4950}51catch52{5354returnfalse;55}56finally57{58if(conn.State ==ConnectionState.Open)59{60conn.Close();61}62}63returnn >0;64}6566publicstaticObject ExecuteScalar(stringsql)//使用ExecuteScalar(),增删改查如果成功,会返回一个对象,否则会返回一个null;67{68Object ob =null;6970try71{72if(conn.State ==ConnectionState.Closed)73{74conn.Open();75}76SqlCommand cmd =newSqlCommand(sql, conn);77ob =cmd.ExecuteScalar();78}79catch80{81returnnull;82}83finally84{85if(conn.State ==ConnectionState.Open)86{87conn.Close();88}89}90returnob;91}92}93}