使用ADO.NET进行数据库update和alter之间的区别添加的核心步骤是什么?


项目
06/09/2015
当您在数据库中创建操作数据的应用程序时,就执行了定义连接字符串、插入数据和运行存储过程等基本任务。 按照本主题,您将了解通过使用 Visual C# 或 Visual Basic 和 ADO.NET 如何与位于一个简单的 Windows 窗体应用程序内的数据交互。重要若要让代码保持简单,请勿包括生产就绪异常处理。主题内容设置示例数据库
创建窗体并添加控件
存储连接字符串
检索连接字符串
为窗体编写代码
测试应用程序
系统必备若要创建应用程序,您需要:Visual Studio 2012 Update 1 或 Visual Studio 2013
SQL Server 2012 Express LocalDB
通过执行 演练:创建小示例数据库 中的以下步骤来创建小型示例数据库。
设置后数据库的连接字符串。 您可通过打开 SQL 服务器对象资源管理器、打开数据库的快捷菜单、选择“属性”并滚动至“连接字符串”属性来找到此值。
本主题假定您已经熟悉 Visual Studio IDE 的基本功能,并可以创建 Windows 窗体应用程序、将窗体添加到项目、将按钮和其他控件安装在这些窗体上、为这些控件设置属性和代码简单的事件。 如果您对这些任务不满意,建议您在开始本主题之前完成 Visual C# 和 Visual Basic 入门。设置示例数据库本演练的示例数据库由客户表和订单表组成。 表最初不包含数据,但是当您要运行将创建的应用程序时就可以添加数据。 该数据库中还有五个简单的存储过程。 演练:创建小示例数据库包含可创建表、主键和外键、约束以及存储过程的 Transact-SQL 脚本。创建窗体并添加控件创建 Windows 窗体应用程序项目,然后将其命名为 SimpleDataApp。
Visual Studio 将创建项目以及若干个文件,包括名为 Form1 的空 Windows 窗体。
添加两个 Windows 窗体到项目中,以使其具有三个窗体,然后对其进行以下名称。
导航
NewCustomer
FillOrCancel
对于每个窗体,添加文本框、按钮和其他控件,如下图所示。 对于每个控件,设置表中描述的特性。
备注分组框和标签控件的清晰性提高,但不在代码中使用。
导航窗体按钮
名称 = btnGoToAdd
按钮
名称 = btnGoToFillOrCancel
按钮
名称 = btnExit
新客户窗体TextBox
名称 = txtCustomerName
TextBox
名称 = txtCustomerID
Readonly = True
按钮
名称 = btnCreateAccount
NumericUpdown
DecimalPlaces = 0
最大值 = 5000
名称 = numOrderAmount
DateTimePicker
格式 = Short
名称 = dtpOrderDate
按钮
名称 = btnPlaceOrder
按钮
名称 = btnAddAnotherAccount
按钮
名称 = btnAddFinish
FillOrCancel 窗体TextBox
名称 = txtOrderID
按钮
名称 = btnFindByOrderID
DateTimePicker
格式 = Short
名称 = dtpFillDate
DataGridView
名称 = dgvCustomerOrders
Readonly = True
RowHeadersVisible = False
按钮
名称 = btnCancelOrder
按钮
名称 = btnFillOrder
按钮
名称 = btnFinishUpdates
存储连接字符串当应用程序尝试打开到数据库的连接时,应用程序必须能够访问连接字符串。 若要避免在每个窗体中手动输入该字符串,请将该字符串存储在项目的应用程序配置文件中,并创建在应用程序任意窗体中调用即可返回该字符串的方法。打开项目的快捷菜单,然后选择**“属性”**。
在“属性”窗口的左面板中,选择“设置”选项卡。
在“名称”列中,输入 connString。
在“类型”列表中,选择“(Connection String)”。
在“范围”列表中,选择“应用程序”。
在“值”列中,输入连接字符串,然后保存更改。
检索连接字符串在菜单栏上,依次选择“项目”、“添加引用”,然后向 System.Configuration.dll 添加引用。
在菜单栏上,依次选择“项目”、“添加类”向项目添加类文件,然后将文件命名为 Utility。
Visual Studio 会创建文件并在“解决方案资源管理器”中显示该文件。
在实用文件中,用下面的代码替换占位符代码。 注意标识代码片段的已编号注释(前缀为 Util-)。 代码后的表明确了要点。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
//Util-1 More namespaces.
using System.Configuration;
namespace SimpleDataApp
{
internal class Utility
{
//Get the connection string from App config file.
internal static string GetConnectionString()
{
//Util-2 Assume failure.
string returnValue = null;
//Util-3 Look for the name in the connectionStrings section.
ConnectionStringSettings settings =
ConfigurationManager.ConnectionStrings["SimpleDataApp.Properties.Settings.connString"];
//If found, return the connection string.
if (settings != null)
returnValue = settings.ConnectionString;
return returnValue;
}
}
}
Imports System
Imports System.Collections.Generic
Imports System.Linq
Imports System.Text
Imports System.Threading.Tasks
' Util-1 More namespaces.
Imports System.Configuration
Namespace SimpleDataApp
Friend Class Utility
' Get connection string from App config file.
Friend Shared Function GetConnectionString() As String
' Util-2 Assume failure.
Dim returnValue As String = Nothing
' Util-3 Look for the name in the connectionStrings section.
Dim settings As ConnectionStringSettings = ConfigurationManager.ConnectionStrings("SimpleDataApp.My.MySettings.connString")
' If found, return the connection string.
If settings IsNot Nothing Then
returnValue = settings.ConnectionString
End If
Return returnValue
End Function
End Class
End Namespace
Util-1
添加 System.Configuration 命名空间。
Util-2
定义一个变量,returnValue,并将其初始化为 null (C#)或 Nothing (Visual Basic)。
Util-3
即使输入 connString 作为“属性”窗口中连接字符串的名称,您仍必须在代码中指定 "SimpleDataApp.Properties.Settings.connString" (C#) 或 "SimpleDataApp.My.MySettings.connString" (Visual Basic)。
为窗体编写代码本节包含了对每个窗体功能的简要概述,并显示生成窗体的代码。 标识代码片段的已编号注释。导航窗体运行应用程序时,导航窗体将打开。 按“添加账户”按钮打开 NewCustomer 窗体。 按“加载或取消订单”按钮打开 FillOrCancel 窗体。 按“退出”按钮关闭应用程序。使“导航”形成启动窗体如果您在“解决方案资源管理器”中使用 C#,则打开 Program.cs,然后将 Application.Run 行更改到此:Application.Run(new Navigation());如果在“解决方案资源管理器”中使用 Visual Basic,请打开“属性”窗口,选择“应用程序” 选项卡,然后在“启动窗体”列表上选择 SimpleDataApp.Navigation。创建事件处理程序为窗体的三个按钮创建空的 Click 事件处理程序。 请参见 如何:在 Windows 窗体设计器上创建默认事件处理程序。为导航创建代码。在“导航”窗体中,用下列代码替换现有代码。using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace SimpleDataApp
{
public partial class Navigation : Form
{
public Navigation()
{
InitializeComponent();
}
//Open the NewCustomer form as a dialog box, which will return focus to the calling form when it closes.
private void btnGoToAdd_Click(object sender, EventArgs e)
{
Form frm = new NewCustomer();
frm.Show();
}
//Open the FillorCancel form as a dialog box.
private void btnGoToFillOrCancel_Click(object sender, EventArgs e)
{
Form frm = new FillOrCancel();
frm.ShowDialog();
}
//Close the application, not just the Navigation form.
private void btnExit_Click(object sender, EventArgs e)
{
this.Close();
}
}
}
Imports System
Imports System.Collections.Generic
Imports System.ComponentModel
Imports System.Data
Imports System.Drawing
Imports System.Linq
Imports System.Text
Imports System.Threading.Tasks
Imports System.Windows.Forms
Namespace SimpleDataApp
Partial Public Class Navigation
Inherits Form
Public Sub New()
InitializeComponent()
End Sub
' Open the NewCustomer form as a dialog box, which will return focus to the calling form when it closes.
Private Sub btnGoToAdd_Click() Handles btnGoToAdd.Click
Dim frm As Form = New NewCustomer()
frm.Show()
End Sub
' Open the FillorCancel form as a dialog box.
Private Sub btnGoToFillOrCancel_Click() Handles btnGoToFillOrCancel.Click
Dim frm As Form = New FillOrCancel()
frm.ShowDialog()
End Sub
' Close the application, not just the Navigation form.
Private Sub btnExit_Click() Handles btnExit.Click
Me.Close()
End Sub
End Class
End Namespace
新客户窗体当您输入客户名并单击“创建帐户”按钮时,NewCustomer 窗体会创建一个客户帐户,而 SQL Server 会返回一个 IDENTITY 值作为新帐户号。 然后通过指定金额和订单日期并选择“下订单”按钮为新帐户下订单。创建事件处理程序为窗体的每个按钮创建空的 Click 事件处理程序。为 NewCustomer 创建代码添加以下代码至 NewCustomer 窗体。 使用编号的注释和代码后的表单步执行每个代码块。using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
//NC-1 More namespaces.
using System.Data.SqlClient;
using System.Configuration;
namespace SimpleDataApp
{
public partial class NewCustomer : Form
{
//NC-2 Storage for IDENTITY values returned from database.
private int parsedCustomerID;
private int orderID;
//NC-3 Specify a connection string.
string connstr = SimpleDataApp.Utility.GetConnectionString();
public NewCustomer()
{
InitializeComponent();
}
//NC-4 Create account.
private void btnCreateAccount_Click(object sender, EventArgs e)
{
//NC-5 Set up and run stored procedure only if Customer Name is present.
if (isCustomerName())
{
//NC-6 Create the connection.
SqlConnection conn = new SqlConnection(connstr);
//NC-7 Create a SqlCommand, and identify it as a stored procedure.
SqlCommand cmdNewCustomer = new SqlCommand("Sales.uspNewCustomer", conn);
cmdNewCustomer.CommandType = CommandType.StoredProcedure;
//NC-8 Add input parameter from the stored procedure and specify what to use as its value.
cmdNewCustomer.Parameters.Add(new SqlParameter("@CustomerName", SqlDbType.NVarChar, 40));
cmdNewCustomer.Parameters["@CustomerName"].Value = txtCustomerName.Text;
//NC-9 Add output parameter.
cmdNewCustomer.Parameters.Add(new SqlParameter("@CustomerID", SqlDbType.Int));
cmdNewCustomer.Parameters["@CustomerID"].Direction = ParameterDirection.Output;
//NC-10 try-catch-finally
try
{
//NC-11 Open the connection.
conn.Open();
//NC-12 Run the stored procedure.
cmdNewCustomer.ExecuteNonQuery();
//NC-13 Customer ID is an IDENTITY value from the database.
this.parsedCustomerID = (int)cmdNewCustomer.Parameters["@CustomerID"].Value;
this.txtCustomerID.Text = Convert.ToString(parsedCustomerID);
}
catch
{
//NC-14 A simple catch.
MessageBox.Show("Customer ID was not returned. Account could not be created.");
}
finally
{
//NC-15 Close the connection.
conn.Close();
}
}
}
//NC-16 Verify that Customer Name is present.
private bool isCustomerName()
{
if (txtCustomerName.Text == "")
{
MessageBox.Show("Please enter a name.");
return false;
}
else
{
return true;
}
}
//NC-17 Place order.
private void btnPlaceOrder_Click(object sender, EventArgs e)
{
//NC-18 Set up and run stored procedure only if required input is present.
if (isPlaceOrderReady())
{
// Create the connection.
SqlConnection conn = new SqlConnection(connstr);
//NC-19 Create SqlCommand and identify it as a stored procedure.
SqlCommand cmdNewOrder = new SqlCommand("Sales.uspPlaceNewOrder", conn);
cmdNewOrder.CommandType = CommandType.StoredProcedure;
//NC-20 @CustomerID, which was an output parameter from uspNewCustomer.
cmdNewOrder.Parameters.Add(new SqlParameter("@CustomerID", SqlDbType.Int));
cmdNewOrder.Parameters["@CustomerID"].Value = this.parsedCustomerID;
//NC-21 @OrderDate.
cmdNewOrder.Parameters.Add(new SqlParameter("@OrderDate", SqlDbType.DateTime, 8));
cmdNewOrder.Parameters["@OrderDate"].Value = dtpOrderDate.Value;
//NC-22 @Amount.
cmdNewOrder.Parameters.Add(new SqlParameter("@Amount", SqlDbType.Int));
cmdNewOrder.Parameters["@Amount"].Value = numOrderAmount.Value;
//NC-23 @Status. For a new order, the status is always O (open)
cmdNewOrder.Parameters.Add(new SqlParameter("@Status", SqlDbType.Char, 1));
cmdNewOrder.Parameters["@Status"].Value = "O";
//NC-24 Add return value for stored procedure, which is the orderID.
cmdNewOrder.Parameters.Add(new SqlParameter("@RC", SqlDbType.Int));
cmdNewOrder.Parameters["@RC"].Direction = ParameterDirection.ReturnValue;
//try – catch - finally
try
{
//Open connection.
conn.Open();
//Run the stored procedure.
cmdNewOrder.ExecuteNonQuery();
//NC-25 Display the order number.
this.orderID = (int)cmdNewOrder.Parameters["@RC"].Value;
MessageBox.Show("Order number " + this.orderID + " has been submitted.");
}
catch
{
//A simple catch.
MessageBox.Show("Order could not be placed.");
}
finally
{
//Close connection.
conn.Close();
}
}
}
//NC-26 Verify that order data is ready.
private bool isPlaceOrderReady()
{
// Verify that CustomerID is present.
if (txtCustomerID.Text == "")
{
MessageBox.Show("Please create customer account before placing order.");
return false;
}
// Verify that Amount isn't 0.
else if ((numOrderAmount.Value < 1))
{
MessageBox.Show("Please specify an order amount.");
return false;
}
else
{
// Order can be submitted.
return true;
}
}
//NC-27 Reset the form for another new account
private void btnAddAnotherAccount_Click(object sender, EventArgs e)
{
this.ClearForm();
}
//NC-28 Clear values from controls
private void ClearForm()
{
txtCustomerName.Clear();
txtCustomerID.Clear();
dtpOrderDate.Value = DateTime.Now;
numOrderAmount.Value = 0;
this.parsedCustomerID = 0;
}
//NC-29 Close the form.
private void btnAddFinish_Click(object sender, EventArgs e)
{
this.Close();
}
}
}
Imports System
Imports System.Collections.Generic
Imports System.ComponentModel
Imports System.Data
Imports System.Drawing
Imports System.Linq
Imports System.Text
Imports System.Threading.Tasks
Imports System.Windows.Forms
' NC-1 More namespaces.
Imports System.Data.SqlClient
Imports System.Configuration
Namespace SimpleDataApp
Partial Public Class NewCustomer
Inherits Form
' NC-2 Storage for IDENTITY values returned from database.
Private parsedCustomerID As Integer
Private orderID As Integer
' NC-3 Specify a connection string.
Private connstr As String = SimpleDataApp.Utility.GetConnectionString()
Public Sub New()
InitializeComponent()
End Sub
' NC-4 Create account.
Private Sub btnCreateAccount_Click() Handles btnCreateAccount.Click
' NC-5 Set up and run stored procedure only if Customer Name is present.
If isCustomerName() Then
' NC-6 Create the connection.
Dim conn As New SqlConnection(connstr)
' NC-7 Create a SqlCommand, and identify it as a stored procedure.
Dim cmdNewCustomer As New SqlCommand("Sales.uspNewCustomer", conn)
cmdNewCustomer.CommandType = CommandType.StoredProcedure
' NC-8 Add input parameter from the stored procedure and specify what to use as its value.
cmdNewCustomer.Parameters.Add(New SqlParameter("@CustomerName", SqlDbType.NVarChar, 40))
cmdNewCustomer.Parameters("@CustomerName").Value = txtCustomerName.Text
' NC-9 Add output parameter.
cmdNewCustomer.Parameters.Add(New SqlParameter("@CustomerID", SqlDbType.Int))
cmdNewCustomer.Parameters("@CustomerID").Direction = ParameterDirection.Output
' NC-10 try-catch-finally
Try
' NC-11 Open the connection.
conn.Open()
' NC-12 Run the stored procedure.
cmdNewCustomer.ExecuteNonQuery()
' NC-13 Customer ID is an IDENTITY value from the database.
Me.parsedCustomerID = CInt(cmdNewCustomer.Parameters("@CustomerID").Value)
Me.txtCustomerID.Text = Convert.ToString(parsedCustomerID)
Catch
' NC-14 A simple catch.
MessageBox.Show("Customer ID was not returned. Account could not be created.")
Finally
' NC-15 Close the connection.
conn.Close()
End Try
End If
End Sub
' NC-16 Verify that Customer Name is present.
Private Function isCustomerName() As Boolean
If txtCustomerName.Text = "" Then
MessageBox.Show("Please enter a name.")
Return False
Else
Return True
End If
End Function
' NC-17 Place order.
Private Sub btnPlaceOrder_Click() Handles btnPlaceOrder.Click
' NC-18 Set up and run stored procedure only if necessary input is present.
If isPlaceOrderReady() Then
' Create the connection.
Dim conn As New SqlConnection(connstr)
' NC-19 Create SqlCommand and identify it as a stored procedure.
Dim cmdNewOrder As New SqlCommand("Sales.uspPlaceNewOrder", conn)
cmdNewOrder.CommandType = CommandType.StoredProcedure
' NC-20 @CustomerID, which was an output parameter from uspNewCustomer.
cmdNewOrder.Parameters.Add(New SqlParameter("@CustomerID", SqlDbType.Int))
cmdNewOrder.Parameters("@CustomerID").Value = Me.parsedCustomerID
' NC-21 @OrderDate.
cmdNewOrder.Parameters.Add(New SqlParameter("@OrderDate", SqlDbType.DateTime, 8))
cmdNewOrder.Parameters("@OrderDate").Value = dtpOrderDate.Value
' NC-22 @Amount.
cmdNewOrder.Parameters.Add(New SqlParameter("@Amount", SqlDbType.Int))
cmdNewOrder.Parameters("@Amount").Value = numOrderAmount.Value
' NC-23 @Status. For a new order, the status is always O (open).
cmdNewOrder.Parameters.Add(New SqlParameter("@Status", SqlDbType.[Char], 1))
cmdNewOrder.Parameters("@Status").Value = "O"
' NC-24 add return value for stored procedure, which is the orderID
cmdNewOrder.Parameters.Add(New SqlParameter("@RC", SqlDbType.Int))
cmdNewOrder.Parameters("@RC").Direction = ParameterDirection.ReturnValue
' try – catch - finally
Try
' Open connection.
conn.Open()
' Run the stored procedure.
cmdNewOrder.ExecuteNonQuery()
' NC-25 Display the order number.
Me.orderID = CInt(cmdNewOrder.Parameters("@RC").Value)
MessageBox.Show("Order number " & (Me.orderID).ToString & " has been submitted.")
Catch
' A simple catch.
MessageBox.Show("Order could not not be placed.")
Finally
' Close connection.
conn.Close()
End Try
End If
End Sub
' NC-26 Verify that order data is ready.
Private Function isPlaceOrderReady() As Boolean
' Verify that CustomerID is present.
If txtCustomerID.Text = "" Then
MessageBox.Show("Please create customer account before placing order.")
Return False
' Verify that Amount isn't 0
ElseIf (numOrderAmount.Value < 1) Then
MessageBox.Show("Please specify an order amount.")
Return False
Else
' Order can be submitted.
Return True
End If
End Function
' NC-27 Reset the form for another new account.
Private Sub btnAddAnotherAccount_Click() Handles btnAddAnotherAccount.Click
Me.ClearForm()
End Sub
' NC-28 Clear values from controls.
Private Sub ClearForm()
txtCustomerName.Clear()
txtCustomerID.Clear()
dtpOrderDate.Value = DateTime.Now
numOrderAmount.Value = 0
Me.parsedCustomerID = 0
End Sub
' NC-29 Close the form.
Private Sub btnAddFinish_Click() Handles btnAddFinish.Click
Me.Close()
End Sub
End Class
End Namespace
NC-1
添加 System.Data.SqlClient 和 System.Configuration 到命名空间列表。
NC-2
声明 parsedCustomerID 和 orderID 变量,待稍后使用。
NC-3
调用 GetConnectionString 方法以从应用程序配置文件中获取连接字符串,并将该值存储在 connstr 字符串变量中。
NC-4
将代码添加至 btnCreateAccount 按钮的单击事件处理程序。
NC-5
将对 isCustomerName 的调用包装在单击事件代码周围,以便让 uspNewCustomer 只在有客户名存在的情况下运行。
NC-6
创建一个 SqlConnection 对象 (conn),并在 connstr 的连接字符串中传递。
NC-7
创建 SqlCommand 对象,cmdNewCustomer。
NC-8
从存储过程添加 @CustomerName 输入参数。
添加参数至 Parameters 集合。
使用 SqlDbType 枚举将参数类型指定为 nvarchar(40)。
将 txtCustomerName.Text 指定为源。
NC-9
从存储过程添加输出参数。
NC-10
添加“Try – Catch – Finally”块打开连接,运行存储过程,处理异常,然后关闭连接。
NC-11
打开在 NC-6 中创建的连接 (conn)。
NC-12
使用 cmdNewCustomer 的 ExecuteNonQuery 方法运行 Sales.uspNewCustomer 存储过程,其中运行的是 INSERT 语句,而不是查询。
NC-13
@CustomerID 值以标识值的形式从数据库返回。 由于是整数,因此,您必须将其转换为字符串以便可以在客户 ID 文本框中显示。
在 NC-2 中声明了 parsedCustomerID。
将 @CustomerID 值存储到 parsedCustomerID 供以后使用。
将返回的客户 ID 转换为字符串并将其插入到 txtCustomerID.Text 中。
NC-14
对于此示例,添加简单而非可投入实际生产运行的 catch 子句。
NC-15
请始终在使用完连接后将其关闭,以便可以将其发布到连接池。 请参阅 SQL Server 连接池 (ADO.NET)。
NC-16
定义一个方法验证客户名是否存在。
NC-17
将代码添加至 btnPlaceOrder 按钮的单击事件处理程序。
NC-18
将对 isPlaceOrderReady 的调用包装在 btnPlaceOrder_Click 事件代码周围,这样如果未输入必需的内容,uspPlaceNewOrder 就不会运行。
通过 NC-25 的 NC-19
代码中的这些部分类似于为 btnCreateAccount_Click 事件处理程序添加的代码。
NC-19。 创建 SqlCommand 对象,cmdNewOrder,并指定 Sales.uspPlaceOrder 作为存储过程。
通过 NC-23 的 NC-20 是存储过程的输入参数。
NC-24。 @RC 将包含从数据库中生成的订单 ID 的返回值。 此参数方向指定为 ReturnValue。
NC-25。 将订单 ID 的值存储在 NC-2 上声明的 orderID 变量中,并在消息框中显示该值。
NC-26
定义一个方法验证客户 ID 是否存在以及在 numOrderAmount 中是否已指定了量。
NC-27
调用 btnAddAnotherAccount 单击事件处理程序中的 ClearForm 方法。
NC-28
如果要添加另一个客户,请创建 ClearForm 方法以清除窗体中的值。
NC29
关闭 NewCustomer 窗体,并使焦点返回到导航窗体。
FillOrCancel 窗体当您输入订单 ID 并选择“查找订单”按钮时,FillorCancel 窗体运行查询并返回订单。 返回的行出现在只读数据网格。 如果您选择“取消订单”按钮,则可以将订单标记为已取消 (X);如果您选择“填写订单”按钮,则可以将订单标记为已填写 (F)。 如果再次选择“查找顺序”按钮,则会显示更新行。创建事件处理程序为窗体的四个按钮创建空的 Click 事件处理程序。为 FillOrCancel 创建代码添加以下代码至 FillOrCancel 窗体。 使用编号的注释和代码后的表单步执行代码块。using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
//FC-1 More namespaces.
using System.Text.RegularExpressions;
using System.Data.SqlClient;
using System.Configuration;
namespace SimpleDataApp
{
public partial class FillOrCancel : Form
{
//FC-2 Storage for OrderID.
private int parsedOrderID;
//FC-3 Specify a connection string.
string connstr = SimpleDataApp.Utility.GetConnectionString();
public FillOrCancel()
{
InitializeComponent();
}
//FC-4 Find an order.
private void btnFindByOrderID_Click(object sender, EventArgs e)
{
//FC-5 Prepare the connection and the command
if (isOrderID())
{
//Create the connection.
SqlConnection conn = new SqlConnection(connstr);
//Define a query string that has a parameter for orderID.
string sql = "select * from Sales.Orders where orderID = @orderID";
//Create a SqlCommand object.
SqlCommand cmdOrderID = new SqlCommand(sql, conn);
//Define the @orderID parameter and its value.
cmdOrderID.Parameters.Add(new SqlParameter("@orderID", SqlDbType.Int));
cmdOrderID.Parameters["@orderID"].Value = parsedOrderID;
//try – catch - finally
try
{
//FC-6 Run the command and display the results.
//Open the connection.
conn.Open();
//Run the command by using SqlDataReader.
SqlDataReader rdr = cmdOrderID.ExecuteReader();
//Create a data table to hold the retrieved data.
DataTable dataTable = new DataTable();
//Load the data from SqlDataReader into the data table.
dataTable.Load(rdr);
//Display the data from the datatable in the datagridview.
this.dgvCustomerOrders.DataSource = dataTable;
//Close the SqlDataReader.
rdr.Close();
}
catch
{
//A simple catch.
MessageBox.Show("The requested order could not be loaded into the form.");
}
finally
{
//Close the connection.
conn.Close();
}
}
}
//FC-7 Cancel an order.
private void btnCancelOrder_Click(object sender, EventArgs e)
{
//Set up and run stored procedure only if OrderID is ready.
if (isOrderID())
{
//Create the connection.
SqlConnection conn = new SqlConnection(connstr);
// Create command and identify it as a stored procedure.
SqlCommand cmdCancelOrder = new SqlCommand("Sales.uspCancelOrder", conn);
cmdCancelOrder.CommandType = CommandType.StoredProcedure;
cmdCancelOrder.Parameters.Add(new SqlParameter("@orderID", SqlDbType.Int));
cmdCancelOrder.Parameters["@orderID"].Value = parsedOrderID;
// try-catch-finally
try
{
// Open the connection.
conn.Open();
// Run the cmdCancelOrder command.
cmdCancelOrder.ExecuteNonQuery();
}
// A simple catch.
catch
{
MessageBox.Show("The cancel operation was not completed.");
}
finally
{
//Close connection.
conn.Close();
}
}
}
//FC-8 Fill an order.
private void btnFillOrder_Click(object sender, EventArgs e)
{
//Set up and run stored procedure only if OrderID is ready.
if (isOrderID())
{
//Create the connection.
SqlConnection conn = new SqlConnection(connstr);
//Create command and identify it as a stored procedure.
SqlCommand cmdFillOrder = new SqlCommand("Sales.uspFillOrder", conn);
cmdFillOrder.CommandType = CommandType.StoredProcedure;
// Add input parameter from the stored procedure.
cmdFillOrder.Parameters.Add(new SqlParameter("@orderID", SqlDbType.Int));
cmdFillOrder.Parameters["@orderID"].Value = parsedOrderID;
//Add the second input parameter.
cmdFillOrder.Parameters.Add(new SqlParameter("@FilledDate", SqlDbType.DateTime, 8));
cmdFillOrder.Parameters["@FilledDate"].Value = dtpFillDate.Value;
//try – catch - finally
try
{
//Open the connection.
conn.Open();
//Run the cmdFillOrder command.
cmdFillOrder.ExecuteNonQuery();
}
catch
{
//A simple catch.
MessageBox.Show("The fill operation was not completed.");
}
finally
{
//Close the connection.
conn.Close();
}
}
}
//FC-9 Verify that OrderID is ready.
private bool isOrderID()
{
//Check for input in the Order ID text box.
if (txtOrderID.Text == "")
{
MessageBox.Show("Please specify the Order ID.");
return false;
}
// Check for characters other than integers.
else if (Regex.IsMatch(txtOrderID.Text, @"^\D*$"))
{
//Show message and clear input.
MessageBox.Show("Please specify integers only.");
txtOrderID.Clear();
return false;
}
else
{
//Convert the text in the text box to an integer to send to the database.
parsedOrderID = Int32.Parse(txtOrderID.Text);
return true;
}
}
//Close the form.
private void btnFinishUpdates_Click(object sender, EventArgs e)
{
this.Close();
}
}
}
Imports System
Imports System.Collections.Generic
Imports System.ComponentModel
Imports System.Data
Imports System.Drawing
Imports System.Linq
Imports System.Text
Imports System.Threading.Tasks
Imports System.Windows.Forms
' FC-1 More namespaces.
Imports System.Text.RegularExpressions
Imports System.Data.SqlClient
Imports System.Configuration
Namespace SimpleDataApp
Partial Public Class FillOrCancel
Inherits Form
' FC-2 Storage for OrderID
Private parsedOrderID As Integer
' FC-3 Specify a connection string
Private connstr As String = SimpleDataApp.Utility.GetConnectionString()
Public Sub New()
InitializeComponent()
End Sub
' FC-4 Find an order.
Private Sub btnFindByOrderID_Click() Handles btnFindByOrderID.Click
' FC-5 Prepare the connection and the command.
If isOrderID() Then
' Create the connection.
Dim conn As New SqlConnection(connstr)
' Define the query string that has a parameter for orderID.
Dim sql As String = "select * from Sales.Orders where orderID = @orderID"
' Create a SqlCommand object.
Dim cmdOrderID As New SqlCommand(sql, conn)
' Define the @orderID parameter and its value.
cmdOrderID.Parameters.Add(New SqlParameter("@orderID", SqlDbType.Int))
cmdOrderID.Parameters("@orderID").Value = parsedOrderID
' try-catch-finally
Try
' FC-6 Run the command and display the results.
' Open connection.
conn.Open()
' Run the command by using SqlDataReader.
Dim rdr As SqlDataReader = cmdOrderID.ExecuteReader()
' Create a data table to hold the retrieved data.
Dim dataTable As New DataTable()
' Load the data from the SqlDataReader into the data table.
dataTable.Load(rdr)
' Display the data from the data table in the datagridview.
Me.dgvCustomerOrders.DataSource = dataTable
' Close the SqlDataReader.
rdr.Close()
Catch
' A simple catch.
MessageBox.Show("The requested order could not be loaded into the form.")
Finally
' Close the connection.
conn.Close()
End Try
End If
End Sub
' FC-7 Cancel an order.
Private Sub btnCancelOrder_Click() Handles btnCancelOrder.Click
' Set up and run stored procedure only if OrderID is ready.
If isOrderID() Then
' Create the connection.
Dim conn As New SqlConnection(connstr)
' Create the command and identify it as a stored procedure.
Dim cmdCancelOrder As New SqlCommand("Sales.uspCancelOrder", conn)
cmdCancelOrder.CommandType = CommandType.StoredProcedure
' Add input parameter from the stored procedure.
cmdCancelOrder.Parameters.Add(New SqlParameter("@orderID", SqlDbType.Int))
cmdCancelOrder.Parameters("@orderID").Value = parsedOrderID
' try-catch-finally
Try
' Open the connection.
conn.Open()
' Run the cmdCancelOrder command.
cmdCancelOrder.ExecuteNonQuery()
Catch
' A simple catch.
MessageBox.Show("The cancel operation was not completed.")
Finally
' Close connection.
conn.Close()
End Try
End If
End Sub
' FC-8 Fill an order.
Private Sub btnFillOrder_Click() Handles btnFillOrder.Click
' Set up and run stored procedure only if OrderID is ready.
If isOrderID() Then
' Create the connection.
Dim conn As New SqlConnection(connstr)
' Create command and identify it as a stored procedure.
Dim cmdFillOrder As New SqlCommand("Sales.uspFillOrder", conn)
cmdFillOrder.CommandType = CommandType.StoredProcedure
' Add input parameter from the stored procedure.
cmdFillOrder.Parameters.Add(New SqlParameter("@orderID", SqlDbType.Int))
cmdFillOrder.Parameters("@orderID").Value = parsedOrderID
' Add second input parameter.
cmdFillOrder.Parameters.Add(New SqlParameter("@FilledDate", SqlDbType.DateTime, 8))
cmdFillOrder.Parameters("@FilledDate").Value = dtpFillDate.Value
' try-catch-finally
Try
' Open the connection.
conn.Open()
' Run the cmdFillOrder command.
cmdFillOrder.ExecuteNonQuery()
Catch
' A simple catch.
MessageBox.Show("The fill operation was not completed.")
Finally
' Close the connection.
conn.Close()
End Try
End If
End Sub
' FC-9 Verify that OrderID is ready.
Private Function isOrderID() As Boolean
' Check for input in the Order ID text box.
If txtOrderID.Text = "" Then
MessageBox.Show("Please specify the Order ID.")
Return False
' Check for characters other than integers.
ElseIf Regex.IsMatch(txtOrderID.Text, "^\D*$") Then
' Show message and clear input.
MessageBox.Show("Please specify integers only.")
txtOrderID.Clear()
Return False
Else
' Convert the text in the text box to an integer to send to the database.
parsedOrderID = Int32.Parse(txtOrderID.Text)
Return True
End If
End Function
' Close the form.
Private Sub btnFinishUpdates_Click() Handles btnFinishUpdates.Click
Me.Close()
End Sub
End Class
End Namespace
FC-1
添加 System.Data.SqlClient、 System.Configuration 和 System.Text.RegularExpressions 到命名空间列表。
FC-2
声明变量 parsedOrderID。
FC-3
调用 GetConnectionString 方法以从应用程序配置文件中获取连接字符串,并将该值存储在 connstr 字符串变量中。
FC-4
添加代码至 btnFindOrderByID 的单击事件处理程序。
FC-5
眼熟? 在尝试运行 SQL 语句或存储过程之前,这些任务都是必需的。
FC-6
此代码使用 SqlDataReader 和 DataTable 检索并显示查询结果。
打开连接。
通过运行 cmdOrderID 的 ExecuteReader 方法创建 SqlDataReader、rdr。
创建 DataTable 对象以保存检索的数据。
将数据从 SqlDataReader 加载到 DataTable 对象。
通过指定 DataTable 作为数据网格视图的 DataSource,显示数据网格视图中的数据。
关闭 SqlDataReader。
FC-7
添加代码至 btnCancelOrder 的单击事件处理程序。 此代码运行 Sales.uspCancelOrder 存储过程。
FC-8
添加代码至 btnFillOrder 的单击事件处理程序。 此代码运行 Sales.uspFillOrder 存储过程。
FC-9
创建一种验证 OrderID 是否准备好作为 SqlCommand 对象的参数提交的方法。
确保 ID 已输入 txtOrderID 中。
使用 Regex.IsMatch 定义非整型字符的简单检查。
在 FC-2 声明了 parsedOrderID 变量。
如果输入有效,则将文本转换为整数,并将值存储在 parsedOrderID 变量中。
将 isOrderID 方法包装在 btnFindByOrderID、btnCancelOrder 和 btnFillOrder 单击事件处理程序周围。
测试应用程序在对每个 Click 事件处理程序进行编码且完成编码后,请选择 F5 键生成并测试应用程序。}

我要回帖

更多关于 数据库update和alter之间的区别 的文章

更多推荐

版权声明:文章内容来源于网络,版权归原作者所有,如有侵权请点击这里与我们联系,我们将及时删除。

点击添加站长微信