您的位置:首页 > 数据库

.NET数据库编程求索之路--3.使用ADO.NET实现(SQL语句篇)(1)

2012-06-10 01:49 806 查看
3.使用ADO.NET实现(SQL语句篇)(1)

  ADO.NET是.NET平台的数据访问技术体系,其是微软在COM時代奠基的OLE DB技術发展而来的。微软在OLE DB之上建立了一个很好的数据存取模型ADO,并被业界接受,如VC6.0、Delphi5/6等都使用ADO数据存取技术。ADO.NET继承了ADO的优点,但它是微软在.NET平台下采用全新的架构和理念构建的。ADO.NET主要通过Connection(连接对象) 、Command(命令对象) 、Parameter(Sql参数) 、DataReader(数据流读取器) 、Transaction(事务) 、DataAdapter(数据适配器) ,以及DataSet,DataTable,DataRow,DataColumn等对象实现对数据库的访问和操纵。发展到今天,ADO.NET已经成为包含Linq、Entity Framework等新一代ORM(Object-Relation Mapping,对象-关系映射)技术的完整体系。就像我们用Linq、Entity Framework来指代新的技术一样,我们还是习惯用ADO.NET一词代表最初的ADO.NET技术。本章即是采用Connection、Command、DataAdapter等最初的ADO.NET技术,通过嵌入SQL语句来实现我们前面给出的示例小系统——订单管理系统。

  本章主要内容:

    从配置文件读取数据连接字符串

    FormMain主窗体代码

    FormEdit添加/修改窗体代码

3.1 从配置文件读取数据连接字符串

  当数据库服务器更换IP地址或登录密码等配置时,应用程序的数据连接字符串也要相应更改,才能正常连接到数据库。如果将数据连接字符串硬编码在程序代码中,就需要重新修改代码并编译程序,这导致应用程序的可移植性非常差。为此,我们通常将数据连接字符串存储在配置文件中,应用程序运行时从配置文件读取连接字符串以实现数据连接。当数据库服务器配置变化时,只需更改配置文件中数据连接参数即可,而不用再修改应用程序代码。
  在“解决方案资源管理器”中单击项目“HomeShop.WinForm”,右键→【添加】→【新建项】,在“添加新项”对话框中选定“应用程序配置文件”项,单击【添加】按钮,则在项目中添加App.Config配置文件,如图3-1。



图3-1 添加应用程序配置文件

在App.Config文件中输入如下代码,建立<connectionStrings>配置节,添加一个名称为“HomeShop”的数据连接字符串。

代码3-1 App.Config

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings>
<add name="HomeShop" connectionString="Data Source=(local1);Initial Catalog=HomeShop;User ID=sa;Password=YourPwd"/>
</connectionStrings>
</configuration>

为实现对<connectionStrings>配置节的读取,需在项目中添加对命名空间“System.Configuration”的引用。在“解决方案资源管理器”中单击项目“HomeShop.WinForm”下的【引用】,右键→【添加引用】,在“添加引用”对话框中的.NET标签页,选中【System.Configuration】后单击【确定】按钮。



图3-2 添加引用

在窗体代码文件FormMain.cs和FormEdit.cs的头部添加“using System.Configuration;”,并为窗体类添加成员变量connectionString,实现对配置文件中数据连接字符串的读取,如代码3-2。

代码3-2 读取配置文件中数据连接字符串

private string connectionString = ConfigurationManager.ConnectionStrings["HomeShop"].ConnectionString;

3.2 FormMain主窗体代码

   代码3-2 FormMain主窗体代码

1 using System;
2 using System.Collections.Generic;
3 using System.ComponentModel;
4 using System.Data;
5 using System.Drawing;
6 using System.Linq;
7 using System.Text;
8 using System.Windows.Forms;
9 using System.Data.SqlClient;//新添命名空间
10 using System.Configuration;//新添命名空间
11
12 namespace HomeShop.WinForm
13 {
14 //功能:订单管理系统-主界面窗体;
15 //作者:夏春涛;
16 //日期:2011-11-30;
17 public partial class FormMain : Form
18 {
19 //数据库连接字符串
20 private string connectionString = ConfigurationManager.ConnectionStrings["HomeShop"].ConnectionString;
21
22 //【窗体构造函数】
23 public FormMain()
24 {
25 InitializeComponent();
26 }
27
28 //【窗体加载事件】
29 private void FormMain_Load(object sender, EventArgs e)
30 {
31 gridView.AutoGenerateColumns = false;//禁止DataGridView控件自动生成列
32 BindData_Orders();//绑定订单列表
33 }
34
35 //绑定订单列表
36 private void BindData_Orders()
37 {
38 txtCustomerName.Clear();
39 SqlConnection connection = new SqlConnection(connectionString);
40 connection.Open();
41 string sql = @"SELECT [OrderID],
42 [CustomerName],
43 [CustomerPhoneNo],
44 [CustomerAddress],
45 [OrderTime],
46 [OrderState].[Name] AS [OrderState]
47 FROM [Order]
48 LEFT OUTER JOIN [OrderState]
49 ON [Order].[OrderStateCode] = [OrderState].[Code]
50 ORDER BY [OrderID] DESC";
51 SqlCommand command = new SqlCommand(sql, connection);
52 SqlDataAdapter adapter = new SqlDataAdapter(command);
53 DataTable dataTable = new DataTable();
54 adapter.Fill(dataTable);
55 connection.Close();
56
57 gridView.DataSource = dataTable;
58 labRecordCount.Text = "共 " + dataTable.Rows.Count.ToString() + " 条记录";
59 }
60
61 //【查询】订单
62 private void btnQuery_Click(object sender, EventArgs e)
63 {
64 if ("" == txtCustomerName.Text.Trim())
65 {
66 MessageBox.Show(this, "请输入要查询的顾客姓名关键词!", "提示",
67 MessageBoxButtons.OK, MessageBoxIcon.Information);
68 txtCustomerName.Focus();
69 return;
70 }
71
72 SqlConnection connection = new SqlConnection(connectionString);
73 connection.Open();
74 string sql = @"SELECT [OrderID],
75 [CustomerName],
76 [CustomerPhoneNo],
77 [CustomerAddress],
78 [OrderTime],
79 [OrderState].[Name] AS [OrderState]
80 FROM [Order]
81 LEFT OUTER JOIN [OrderState]
82 ON [Order].[OrderStateCode] = [OrderState].[Code]
83 WHERE [CustomerName] LIKE @CustomerName
84 ORDER BY [OrderID] DESC";
85 SqlCommand command = new SqlCommand(sql, connection);
86 command.Parameters.Add(new SqlParameter("@CustomerName", "%" + txtCustomerName.Text.Trim() + "%"));
87 SqlDataAdapter adapter = new SqlDataAdapter(command);
88 DataTable dataTable = new DataTable();
89 adapter.Fill(dataTable);
90 connection.Close();
91
92 gridView.DataSource = dataTable;
93 labRecordCount.Text = "共 " + dataTable.Rows.Count.ToString() + " 条记录";
94 }
95
96 //【全部显示】订单
97 private void btnShowAll_Click(object sender, EventArgs e)
98 {
99 BindData_Orders();
100 }
101
102 //【新增】订单
103 private void menuAdd_Click(object sender, EventArgs e)
104 {
105 FormEdit formEdit = new FormEdit();
106 DialogResult dlgResult = formEdit.ShowDialog(this);//显示为模式对话框
107 if (DialogResult.OK == dlgResult)
108 {
109 BindData_Orders();//重新绑定订单列表
110 }
111 formEdit.Dispose();//释放窗体资源
112 }
113
114 //【修改】订单
115 private void menuUpdate_Click(object sender, EventArgs e)
116 {
117 if (gridView.RowCount == 0) return;
118
119 int selectedRowIndex = gridView.SelectedRows[0].Index;
120 int selectedOrderID = (int)gridView.SelectedRows[0].Cells["Col_OrderID"].Value;
121 FormEdit formEdit = new FormEdit(selectedOrderID); //指定要修改的订单ID
122 DialogResult dlgResult = formEdit.ShowDialog(this);//显示为模式对话框
123 if (DialogResult.OK == dlgResult)
124 {
125 BindData_Orders();//重新绑定订单列表
126 gridView.Rows[selectedRowIndex].Selected = true;//依然选中当前行
127 }
128 formEdit.Dispose();//释放窗体资源
129 }
130
131 //【删除】订单
132 private void menuDelete_Click(object sender, EventArgs e)
133 {
134 if (gridView.RowCount == 0) return;
135
136 int selectedRowIndex = gridView.SelectedRows[0].Index;
137 int selectedOrderID = (int)gridView.SelectedRows[0].Cells["Col_OrderID"].Value;
138 DialogResult dlgResult = MessageBox.Show(this, "确认要删除选中的订单吗?", "提示",
139 MessageBoxButtons.YesNo, MessageBoxIcon.Question);
140 if (DialogResult.Yes == dlgResult)
141 {
142 DeleteOrder(selectedOrderID);//删除订单
143 BindData_Orders();//重新绑定订单列表
144 //选中下一条记录
145 if (selectedRowIndex > gridView.Rows.Count - 1)
146 selectedRowIndex = gridView.Rows.Count - 1;
147 if (selectedRowIndex >= 0)
148 {
149 gridView.Rows[selectedRowIndex].Selected = true;
150 }
151 }
152 }
153
154 //删除订单
155 private int DeleteOrder(int orderID)
156 {
157 int rowsCountAffected = 0;
158 SqlConnection connection = new SqlConnection(connectionString);
159 connection.Open();
160 string sql = @"DELETE FROM [OrderItem]
161 WHERE [OrderID] = @OrderID
162
163 DELETE FROM [Order]
164 WHERE [OrderID] = @OrderID ";
165 SqlCommand command = new SqlCommand(sql, connection);
166 command.Parameters.Add(new SqlParameter("@OrderID", orderID));
167 //开始数据库事务
168 SqlTransaction trans = connection.BeginTransaction();
169 command.Transaction = trans;
170 try
171 {
172 rowsCountAffected = command.ExecuteNonQuery();
173 trans.Commit();//提交数据库事务
174 }
175 catch
176 {
177 trans.Rollback();//回滚数据库事务
178 throw;
179 }
180 connection.Close();
181
182 return rowsCountAffected;
183 }
184 }
185 }

转载请注明:【 夏春涛 email: xchuntao@163.com blog: http://www.cnblogs.com/SummerRain

数据库文件:/Files/SummerRain/NetDbDevRoad/HomeShopDB.rar

完整源代码:/Files/SummerRain/NetDbDevRoad/3使用ADONET实现SQL语句篇.rar
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐