C#連接數據庫是編寫的SqlHelper
static class SqlHelper
{
private static string connStr = ConfigurationManager.ConnectionStrings["dbConStr"].ConnectionString;
//封裝方法的原則:把不變的放在方法裡 變化的放到參數列表中
public static int ExecuteNonQuery(string sql, params SqlParameter[] parameters)
{
using (SqlConnection coon = new SqlConnection(connStr))
{
coon.Open();
using (SqlCommand cmd = coon.CreateCommand())
{
cmd.CommandText = sql;
cmd.Parameters.AddRange(parameters);
return cmd.ExecuteNonQuery();
}
}
}
public static object ExecuteScalar(string sql, params SqlParameter[] parameters)
{
using (SqlConnection coon = new SqlConnection(connStr))
{
coon.Open();
using (SqlCommand cmd = coon.CreateCommand())
{
cmd.CommandText = sql;
cmd.Parameters.AddRange(parameters);
return cmd.ExecuteScalar();
}
}
}
//由於查詢的比較小 所以 可以直接用Table
public static DataTable ExecuteDataTable(string sql, params SqlParameter[] parameters)
{
using (SqlConnection coon = new SqlConnection(connStr))
{
coon.Open();
using (SqlCommand cmd = coon.CreateCommand())
{
cmd.CommandText = sql;
cmd.Parameters.AddRange(parameters);
DataSet dataset = new DataSet();
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
adapter.Fill(dataset);
return dataset.Tables[0];
}
}
}