最简单的dbhelper类
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.Data;
namespace MyBookShop.DAL {
public class DBHelper {
private static SqlConnection connection;
public static SqlConnection Connection {
get { string connectionString = "server=.;database=MyBookShop;uid=sa;pwd=accp";
if (connection == null)
{ connection = new SqlConnection(connectionString);
connection.Open();
}
else if (connection.State == ConnectionState.Closed) { connection.Open(); } else if (connection.State == ConnectionState.Broken) { connection.Close(); connection.Open();
}
return connection; } }
public static int ExecuteCommand(string sql) { SqlCommand cmd = new SqlCommand(sql, Connection); int result = cmd.ExecuteNonQuery(); return result; }
public static int ExecuteCommand(string sql, params SqlParameter[] values) { SqlCommand cmd = new SqlCommand(sql, Connection);
cmd.Parameters.AddRange(values); return cmd.ExecuteNonQuery();
}
public static int GetScalar(string sql) { SqlCommand cmd = new SqlCommand(sql, Connection); int result = Convert.ToInt32(cmd.ExecuteScalar()); return result;
}
public static int GetScalar(params SqlParameter[] values) { SqlCommand cmd = new SqlCommand(); cmd.Connection = Connection; cmd.CommandText = "Pro_InsertOrder"; cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddRange(values); int result = Convert.ToInt32(cmd.ExecuteScalar()); return result; }
public static int GetScalar(string sql, params SqlParameter[] values) { SqlCommand cmd = new SqlCommand(sql, Connection); cmd.Parameters.AddRange(values); int result = Convert.ToInt32(cmd.ExecuteScalar()); return result;
}
public static SqlDataReader GetReader(string sql) { SqlCommand cmd = new SqlCommand(sql, Connection); SqlDataReader reader = cmd.ExecuteReader(); return reader; }
public static SqlDataReader GetReader(string sql, params SqlParameter[] values) { SqlCommand cmd = new SqlCommand(sql, Connection); cmd.Parameters.AddRange(values); SqlDataReader reader = cmd.ExecuteReader(); return reader; }
public static DataTable GetTableSet(string sql) { DataSet ds = new DataSet(); SqlCommand cmd = new SqlCommand(sql, Connection); SqlDataAdapter da = new SqlDataAdapter(cmd); da.Fill(ds); return ds.Tables[0];
}
public static DataTable GetTableSet(string sql, params SqlParameter[] values) { DataSet ds = new DataSet(); SqlCommand cmd = new SqlCommand(sql, Connection); cmd.Parameters.AddRange(values); SqlDataAdapter da = new SqlDataAdapter(cmd); da.Fill(ds); return ds.Tables[0]; }
} }