本文主要给官方技术手册填个坑。
https://docs.microsoft.com/zh-CN/visualstudio/data-tools/create-a-simple-data-application-by-using-adonet?view=vs-2019&tabs=csharp
以上是原技术手册内容。
在跟着技术手册走时,在
添加适用于 NewCustomer 窗体逻辑的代码
部分,有一个地方巨坑。
using (SqlConnection connection = new SqlConnection(Properties.Settings.Default.connString))
{
// Create a SqlCommand, and identify it as a stored procedure.
using (SqlCommand sqlCommand = new SqlCommand("Sales.uspNewCustomer", connection))
{
sqlCommand.CommandType = CommandType.StoredProcedure;
// Add input parameter for the stored procedure and specify what to use as its value.
sqlCommand.Parameters.Add(new SqlParameter("@CustomerName", SqlDbType.NVarChar, 40));
sqlCommand.Parameters["@CustomerName"].Value = txtCustomerName.Text;
// Add the output parameter.
sqlCommand.Parameters.Add(new SqlParameter("@CustomerID", SqlDbType.Int));
sqlCommand.Parameters["@CustomerID"].Direction = ParameterDirection.Output;
try
{
connection.Open();
// Run the stored procedure.
sqlCommand.ExecuteNonQuery();
// Customer ID is an IDENTITY value from the database.
this.parsedCustomerID = (int)sqlCommand.Parameters["@CustomerID"].Value;
// Put the Customer ID value into the read-only text box.
this.txtCustomerID.Text = Convert.ToString(parsedCustomerID);
}
catch
{
MessageBox.Show("Customer ID was not returned. Account could not be created.");
}
finally
{
connection.Close();
}
}
}
以上是官方原写法,如果没有获得前面一个GitHub里的脚本而自己创建数据库的话,那这里将执行失败,无法对数据库进行操作。
主要问题在于:
using (SqlCommand sqlCommand = new SqlCommand("Sales.uspNewCustomer", connection))
{
sqlCommand.CommandType = CommandType.StoredProcedure;
在以上中,官方使用了StoredProcedure方法。那么,SqlCommand(“Sales.uspNewCustomer”,connection)中的Sales.uspNewCustomer就并非transact语句了,而是一个在前面对表格定义的函数的名字,这个函数的作用是存储,所需的参数由sqlcommand的add方法传入其中。
如果要用传统意义上的transact语句,就必须删掉sqlCommand.CommandType = CommandType.StoredProcedure;
这一句,因为这一句将sqlcommand定义为引用了一个存储函数,这个函数是需要在前面声明函数方法的,如果前面未声明这个函数,则数据库将无法执行操作。
同时,
sqlCommand.Parameters["@CustomerID"].Direction = ParameterDirection.Output;
此语句也将无法使用。
那么为了实现该语句的功能,我选择在try语句中先获取表格行数作为ID,再执行添加数据的操作。如下:
try
{
conn.Open();
SqlCommand smd = new SqlCommand("SELECT COUNT(*) FROM uspNewCustomer", conn) ;
int cout = Convert.ToInt32(smd.ExecuteScalar());
sqlcmd.Parameters["@CustomerID"].Value = cout;
sqlcmd.ExecuteNonQuery();
CustomerID.Text = Convert.ToString(sqlcmd.Parameters["@CustomerID"].Value);
}
经过本人测试可以实现官方技术文档的功能。
当然,总的来说,还是因为本人对该方面掌握不深,但是我想向我一样疑惑的人也不在少数,希望能帮到各位和我一样入门级的选手。