How to call SQL Server stored procedures in ASP.NET( VB .NET)

Resource: http://support.microsoft.com/kb/306574

For more information, see the following topics in the Microsoft .NET Framework Software Development Kit (SDK) documentation:
  • For more general information about ADO.NET or Visual Basic .NET, refer to the following MSDN newsgroups:
microsoft.public.dotnet.framework.adonet (http://go.microsoft.com/fwlink/?linkid=5819)

microsoft.public.dotnet.languages.vb (http://go.microsoft.com/fwlink/?linkid=5820)
  • For more information, see the following book:
Wyke, R. Allen, and Sultan Rehman and Brad Leupen. XML Programming (Core Reference) (http://go.microsoft.com/fwlink/?LinkId=8394 ). Microsoft Press, 2001.
  • For more information, see the following Microsoft Training & Certification course:
2389 Programming with ADO.NET (http://www.microsoft.com/learning/syllabi/en-us/2389Bfinal.mspx)
  • For additional information about how to perform this task by using Microsoft Active Server Pages, click the article number below to view the article in the Microsoft Knowledge Base:
300488 (http://support.microsoft.com/kb/300488/EN-US/) How To Run SQL Stored Procedures from an ASP Page
[@more@]

Create an ASP.NET Project and Add Controls

In this section, you create an ASP.NET project and build the basic user interface. Note that these steps use Microsoft Visual Basic .NET code. To create the project, follow these steps:
1.Click Start, point to Programs, point to Microsoft Visual Studio .NET, and then click Microsoft Visual Studio .NET.
2.On the Visual Studio .NET Start page, click New Project.
3.In the New Project dialog box, click Visual Basic Projects under Project Types, and then click ASP.NET Web Application under Templates.
4.In the Name box, type a name for your Web application, and then click OK.
5.Add the following server controls to the Web Form, and set the properties as they are listed in the table:
ControlID PropertyText Property
LabellblLastNameType the Author's Last Name:
TextBoxtxtLastName%
ButtonbtnGetAuthorsGet Authors
LabellblRowCount(Row Count)
6.Drag a DataGrid server control from the toolbox to the Web Form, and then set the Name property to GrdAuthors.
7.Right-click the grid, and then click Autoformat.
8.Click Professional 1 for the scheme, and then click OK.

Create the GetAuthorsByLastName Stored Procedure

Use the following Transact-SQL code to create the GetAuthorsByLastName stored procedure:
Create Procedure GetAuthorsByLastName1 (@au_lname varchar(40), @RowCount int output)  
as

select * from authors where au_lname like @au_lname;

/* @@ROWCOUNT returns the number of rows that are affected by the last statement. */
select @RowCount=@@ROWCOUNT

This code includes two parameters: @au_lname and @RowCount. The @au_lname parameter is an input parameter that obtains the search string to perform a "like" search in the Authors table. The @RowCount parameter is an output parameter that uses the @@ROWCOUNT variable to obtain the affected rows.

Create and Run the Stored Procedure

To access SQL Server databases, you must import the System.Data.SqlClient namespace, which provides new objects such as the SqlDataReader and the SqlDataAdapter objects. You can use SqlDataReader to read a forward-only stream of rows from a SQL Server database. DataAdapter represents a set of data commands and a database connection that you can use to fill the DataSet object and to update a SQL Server database.

ADO.NET also introduces the DataSet object, which is a memory-resident representation of data that provides a consistent, relational programming model regardless of the data source. The code in this section uses all of these objects.
1.Double-click the Web Form.
2.Add the following code to the Declaration section of your Web Form, which appears at the top of the Code window:
Imports System.Data
Imports System.Data.SqlClient
3.To make sure that the stored procedure exists and to create a new stored procedure, use a SqlCommand object with a SqlDataReader object. You can use SqlCommand to run any SQL commands against the database. Then call the ExecuteReader method of SqlCommand to return SqlDataReader, which contains matching rows for your query.

Add the following code in the Page_Load event of the Web Form:
'Only run this code the first time the page is loaded.
'The code inside the IF statement is skipped when you resubmit the page.
If Not IsPostBack Then
Dim MyConnection As SqlConnection
Dim MyCommand As SqlCommand
Dim MyDataReader As SqlDataReader

'Create a Connection object.
MyConnection = New SqlConnection("server=(local);database=pubs;Trusted_Connection=yes")

'Create a Command object, and then set the connection.
'The following SQL statements check whether a GetAuthorsByLastName stored procedure
'already exists.
MyCommand = New SqlCommand("if object_id('pubs..GetAuthorsByLastName') is not null " + "begin" + " if objectproperty(object_id('pubs..GetAuthorsByLastName'), 'IsProcedure')= 1" + " select object_id('pubs..GetAuthorsByLastName')" + " else" + " return " + "end" + " else" + " return", MyConnection)

With MyCommand
'Set the command type that you will run.
.CommandType = CommandType.Text

'Open the connection.
.Connection.Open()

'Run the SQL statement, and then get the returned rows to the DataReader.
MyDataReader = .ExecuteReader()

'If any rows are retuned, the stored procedure that you are trying
'to create already exists. Therefore, try to create the stored procedure
'only if it does not exist.
If Not MyDataReader.Read() Then
.CommandText = "create procedure GetAuthorsByLastName (@au_lname varchar(40), " & _

"@RowCount int output) " & _

" as select * from authors where au_lname like @au_lname; select @RowCount=@@ROWCOUNT"
MyDataReader.Close()
.ExecuteNonQuery()
Else
MyDataReader.Close()
End If

.Dispose() 'Dispose of the Command object.
MyConnection.Close() 'Close the connection.
End With
End If
4.Call the stored procedure in the Click event of the btnGetAuthors button, and then use the SqlDataAdapter object to run your stored procedure. You must create parameters for the stored procedure and append it to the Parameters collection of the SqlDataAdapter object.

Add the following code after the Page_Load event:
Private Sub btnGetAuthors_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles btnGetAuthors.Click
Dim DS As DataSet
Dim MyConnection As SqlConnection
Dim MyDataAdapter As SqlDataAdapter

'Create a connection to the SQL Server.
MyConnection = New SqlConnection("server=(local);database=pubs;Trusted_Connection=yes")

'Create a DataAdapter, and then provide the name of the stored procedure.
MyDataAdapter = New SqlDataAdapter("GetAuthorsByLastName", MyConnection)

'Set the command type as StoredProcedure.
MyDataAdapter.SelectCommand.CommandType = CommandType.StoredProcedure

'Create and add a parameter to Parameters collection for the stored procedure.
MyDataAdapter.SelectCommand.Parameters.Add(New SqlParameter("@au_lname", _
SqlDbType.VarChar, 40))

'Assign the search value to the parameter.
MyDataAdapter.SelectCommand.Parameters("@au_lname").Value = Trim(txtLastName.Text)

'Create and add an output parameter to Parameters collection.
MyDataAdapter.SelectCommand.Parameters.Add(New SqlParameter("@RowCount", _
SqlDbType.Int, 4))

'Set the direction for the parameter. This parameter returns the Rows returned.
MyDataAdapter.SelectCommand.Parameters("@RowCount").Direction = ParameterDirection.Output

DS = New DataSet() 'Create a new DataSet to hold the records.
MyDataAdapter.Fill(DS, "AuthorsByLastName") 'Fill the DataSet with the rows returned.

'Get the number of rows returned, and then assign it to the Label control.
'lblRowCount.Text = DS.Tables(0).Rows.Count().ToString() & " Rows Found!"
lblRowCount.Text = MyDataAdapter.SelectCommand.Parameters(1).Value & " Rows Found!"

'Set the data source for the DataGrid as the DataSet that holds the rows.
Grdauthors.DataSource = DS.Tables("AuthorsByLastName").DefaultView

'Bind the DataSet to the DataGrid.
'NOTE: If you do not call this method, the DataGrid is not displayed!
Grdauthors.DataBind()

MyDataAdapter.Dispose() 'Dispose of the DataAdapter.
MyConnection.Close() 'Close the connection.
End Sub
5.In Solution Explorer, right-click the .aspx page, and then click Set as Start Page.
6.Save the project, and then click Start in Visual Studio .NET. Notice that the project is compiled and that the default page runs.
7.Type the author's last name in the text box, and then click Get Author. Notice that the stored procedure is called and that the returned rows populate the DataGrid.

You can provide SQL Server-type search strings such as G%, which returns all the authors by last names that start with the letter "G."
If you cannot connect to the database, make sure that the ConnectionString properly points to the server that is running SQL Server.
If you can connect to the database, but if you experience problems when you try to create the stored procedure, make sure that you have the correct permissions to create stored procedures in the database to which you are connecting.

来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/1697933/viewspace-893889/,如需转载,请注明出处,否则将追究法律责任。

转载于:http://blog.itpub.net/1697933/viewspace-893889/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
基于PyTorch的Embedding和LSTM的自动写诗实验LSTM (Long Short-Term Memory) 是一种特殊的循环神经网络(RNN)架构,用于处理具有长期依赖关系的序列数据。传统的RNN在处理长序列时往往会遇到梯度消失或梯度爆炸的问题,导致无法有效地捕捉长期依赖。LSTM通过引入门控机制(Gating Mechanism)和记忆单元(Memory Cell)来克服这些问题。 以下是LSTM的基本结构和主要组件: 记忆单元(Memory Cell):记忆单元是LSTM的核心,用于存储长期信息。它像一个传送带一样,在整个链上运行,只有一些小的线性交互。信息很容易地在其上保持不变。 输入门(Input Gate):输入门决定了哪些新的信息会被加入到记忆单元中。它由当前时刻的输入和上一时刻的隐藏状态共同决定。 遗忘门(Forget Gate):遗忘门决定了哪些信息会从记忆单元中被丢弃或遗忘。它也由当前时刻的输入和上一时刻的隐藏状态共同决定。 输出门(Output Gate):输出门决定了哪些信息会从记忆单元中输出到当前时刻的隐藏状态中。同样地,它也由当前时刻的输入和上一时刻的隐藏状态共同决定。 LSTM的计算过程可以大致描述为: 通过遗忘门决定从记忆单元中丢弃哪些信息。 通过输入门决定哪些新的信息会被加入到记忆单元中。 更新记忆单元的状态。 通过输出门决定哪些信息会从记忆单元中输出到当前时刻的隐藏状态中。 由于LSTM能够有效地处理长期依赖关系,它在许多序列建模任务中都取得了很好的效果,如语音识别、文本生成、机器翻译、时序预测等。
.NET Core 中,可以使用 ADO.NET 访问 SQL Server 数据库和存储过程。以下是一个简单的示例,演示如何使用 ADO.NET 调用 SQL Server 存储过程: ```csharp using System; using System.Data; using System.Data.SqlClient; namespace ConsoleApp { class Program { static void Main(string[] args) { // 连接字符串 string connectionString = "Data Source=<server>;Initial Catalog=<database>;User ID=<username>;Password=<password>"; // 存储过程名称 string storedProcedureName = "GetPersonsByLastName"; // 创建连接对象和命令对象 using (SqlConnection connection = new SqlConnection(connectionString)) using (SqlCommand command = new SqlCommand(storedProcedureName, connection)) { // 设置命令类型为存储过程 command.CommandType = CommandType.StoredProcedure; // 添加输入参数 SqlParameter parameter = new SqlParameter("@LastName", SqlDbType.VarChar, 50); parameter.Value = "S%"; command.Parameters.Add(parameter); // 打开连接 connection.Open(); // 执行命令并获取结果集 SqlDataReader reader = command.ExecuteReader(); // 遍历结果集 while (reader.Read()) { int id = reader.GetInt32(0); string firstName = reader.GetString(1); string lastName = reader.GetString(2); Console.WriteLine($"Id: {id}, FirstName: {firstName}, LastName: {lastName}"); } // 关闭连接和读取器 reader.Close(); connection.Close(); } Console.ReadLine(); } } } ``` 在上面的示例中,我们使用 SqlConnection 和 SqlCommand 对象来创建连接和执行存储过程。我们设置命令类型为存储过程,并添加一个输入参数。然后,我们打开连接并执行命令,然后遍历结果集并输出每个人员的信息。最后,我们关闭连接和读取器。 请注意,存储过程名称和连接字符串需要根据实际情况进行修改。此外,可以根据需要添加更多的输入参数和输出参数。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值