先写一个数据库统计函数
Code
1public static int Count(string cityName)
2 {
3 string cmdText = "";
4 SqlConnection conn = new SqlConnection(DBH.DBA);
5 SqlCommand cmd = null;
6
7
8 cmdText = "Select count(*) From [Drugstore] Where CityName=@cityName ";
9 cmd = new SqlCommand(cmdText, conn);
10 cmd.Parameters.AddWithValue("@cityName", cityName);
11 conn.Open();
12 int total = (int)cmd.ExecuteScalar();
13 conn.Close();
14 return total;
15 }
16
刚开始全部函数调用是这样一个个写出来的,后来熟悉了 用SqlHelp方便好多,在后来就直接用动软.net代码生成器了,发现对原先的这些越来越陌生了 ,现在大致整理一下,和上面重复的代码部分省略。
1. 添加数据
Code
1 DrugstoreInfo info = new DrugstoreInfo();
2 cmd.Parameters.AddWithValue("@ID",info.ID);
3 try
4 {
5 conn.Open();
6 return cmd.ExecuteNonQuery();
7 }
8 catch
9 {
10 throw;
11 }
12 finally
13 {
14 conn.Close();
15 }
2.dataset 数据分页
Code
1 public static DataSet indexQuery(int pageIndex, int pageSize)
2{
3 ..
4 SqlDataAdapter da = new SqlDataAdapter(cmd);
5 DataSet ds = new DataSet();
6 da.Fill(ds, (pageIndex - 1) * pageSize, pageSize, "Table1");
7 return ds;
8}
3. 获得最大值
Code
1 public static int GetMax()
2 {
3 string cmdText = "select Max(Id) from Application ";
4 ..
5 try
6 {
7 conn.Open();
8 Object obj = cmd.ExecuteScalar();
9 if (obj == null || obj is DBNull)
10 {
11 return 1;
12 }
13 return (int)obj + 1;
14 }
15 catch
16 {
17 throw;
18 }
19 finally
20 {
21 conn.Close();
22 }
23 }
4. select 选择
Code
1public static ApplicationInfo Select(int id)
2 {
3 string cmdText = "select ID from Application where ID=@ID";
4 SqlConnection conn = new SqlConnection(DBH.ConnString);
5 SqlCommand cmd = new SqlCommand(cmdText, conn);
6 ApplicationInfo info = new ApplicationInfo();
7 cmd.Parameters.AddWithValue("@ID", id);
8 conn.Open();
9 using (IDataReader dr = cmd.ExecuteReader())
10 {
11 if (dr.Read())
12 {
13 info.ID = (int)dr["ID"];
14 }
15 dr.Close();
16 }
17 conn.Close();
18
19 return info;
20 }
5.delete 删除
Code
1 public static int Del(int id)
2 {
3 string cmdText = "Delete from Application Where ID= @ID";
4 SqlConnection conn = new SqlConnection(DBH.ConnString);
5 SqlCommand cmd = new SqlCommand(cmdText, conn);
6 cmd.Parameters.AddWithValue("@ID", id);
7 conn.Open();
8 return cmd.ExecuteNonQuery();
9 conn.Close();
10 }
6. update 修改
Code
public static int Update(ApplicationInfo info)
{
string cmdText = "Update Application Set City=@city Where ID=@ID";
SqlConnection conn = new SqlConnection(DBH.ConnString);
SqlCommand cmd = new SqlCommand(cmdText, conn);
cmd.Parameters.AddWithValue("@ID", info.ID);
try
{
conn.Open();
return cmd.ExecuteNonQuery();
}
catch
{
throw;
}
finally
{
conn.Close();
}
}
7.配置
Code
1 public class DBH
2 {
3 private DBH() { }
4 private static readonly string _DBA = ConfigurationManager.ConnectionStrings["DBA"].ConnectionString;
5 public static string DBA
6 {
7 get { return _DBA; }
8 }
9 }
附: configurationManager 需要命名空间 using System.Configuration 和添加引用System.Configuration 双重操作。