Execute Stored Procedure OnClick - asp.net

How can I execute a stored procedure on OnClick button with no parameters? I have the following code behind:
Protected Sub btnExport_Click(sender As Object, e As System.EventArgs) Handles btnExport.Click
Dim exec As SqlCommand = New SqlCommand("up_ExportFile", conn)
exec.CommandType = CommandType.StoredProcedure
End Sub

Supposing you have already opened the connection just add the ExecuteNonQuery method
Protected Sub btnExport_Click(sender As Object, e As System.EventArgs) Handles btnExport.Click
Dim exec As SqlCommand = New SqlCommand("up_ExportFile", conn)
exec.CommandType = CommandType.StoredProcedure
exec.ExecuteNonQuery()
End Sub
However I suggest you to not keep a global variable holding your SqlConnection opened for the lifetime of your application. Remember that the ADO.NET provider for SqlServer implements the connection pooling mechanism and thus, opening a connection is a lightweight procedure.
So a better approach is
Using conn = new SqlConnection("your_connection_string_here")
conn.Open()
Dim exec As SqlCommand = New SqlCommand("up_ExportFile", conn)
exec.CommandType = CommandType.StoredProcedure
exec.ExecuteNonQuery()
End Using
In this way the connection object is created just when needed, and then closed and disposed
See Using Statememt

Related

Can't read data from SQL Server database

I'm having a problem when I'm reading data from a SQL Server database. The main thing is that I want to read the data from the database and display the data in a Label control. But the concern is that it can't read data to it. I will show you the code snippet and any comments/suggestions are gladly considered.
Option Explicit On
Imports System.Data
Imports System.Data.OleDb
Partial Class ViewDetail
Inherits System.Web.UI.Page
Dim con As OleDbConnection
Dim cmd As OleDbCommand
Dim dr As OleDbDataReader
Dim InstructorID As Integer
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
InstructorID = Request.QueryString("Instructor_ID")
Integer.TryParse(lblID.Text, InstructorID)
con = New OleDbConnection("Provider=SQLNCLI11;Data Source=ARIES-PC\SQLEXPRESS;Integrated Security=SSPI;Initial Catalog=SchoolDB")
con.Open()
cmd = New OleDbCommand("SelectData", con)
cmd.CommandType = CommandType.StoredProcedure
cmd.Parameters.AddWithValue("#id", InstructorID)
dr = cmd.ExecuteReader
If dr.HasRows Then
While dr.Read
lblID.Text = dr("Instructor_ID").ToString
lblFirstname.Text = dr("FirstName").ToString
lblLastname.Text = dr("LastName").ToString
lblAddress.Text = dr("Address").ToString
lblContact.Text = dr("Contact_Number").ToString
End While
End If
dr.Close()
cmd.Dispose()
con.Close()
End Sub
End Class
This line seems to be totally wrong
Integer.TryParse(lblID.Text, InstructorID)
This lines takes the current value in the lblID.Text at the Page_Load event and tries to set the value of InstructorID. But your code seems to want this value from the QueryString passed that contains the real value.
If you are certain the the QueryString contains a valid integer then remove that line and add
InstructorID = Convert.ToInt32(Request.QueryString("Instructor_ID"))

asp.net update with datareader don't work

i want to change textbox information but when i try to do that it's don't work
this is my asp.net vb code
Imports System.Data.SqlClient
Imports System.Data
Imports System.Data.SqlClient.SqlDataReader
Partial Class _Default
Inherits System.Web.UI.Page
Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim connectionString As String = "Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\napster\Documents\ZE.mdf;Integrated Security=True;Connect Timeout=30"
Dim queryString As String = "Update TEST Set chaine1= '" & TextBox1.Text & "' "
Dim connection As New SqlConnection(connectionString)
Dim command As New SqlCommand(queryString, connection)
connection.Open()
command.ExecuteNonQuery()
connection.Close()
End Sub
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
Dim connectionString As String = "Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\napster\Documents\ZE.mdf;Integrated Security=True;Connect Timeout=30"
Dim queryString As String = "SELECT * from TEST "
Dim connection As New SqlConnection(connectionString)
Dim command As New SqlCommand(queryString, connection)
connection.Open()
Dim dataReader As SqlDataReader = command.ExecuteReader()
While dataReader.Read()
TextBox1.Text = dataReader.GetSqlString(3)
End While
TextBox1.
End Sub
End Class
You should always consider how the ASP.NET model works.
In ASP.NET, when you click a button that executes a server side code (the event) you get always a call to the Page.Load event before the call to your event handler code.
In your Page.Load you execute again the code to load the TextBox from the database, but this code destroys the content of the textbox that has been typed by you. The textbox is set to the original value extracted by the database, so, when the code in the button event handler is executed it writes the same value to the database.
To resolve this situation you need to add this to the Page_Load event
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
if Not IsPostBack Then
Dim connectionString As String = "......"
Dim queryString As String = "SELECT * from TEST "
Dim connection As New SqlConnection(connectionString)
Dim command As New SqlCommand(queryString, connection)
connection.Open()
Dim dataReader As SqlDataReader = command.ExecuteReader()
While dataReader.Read()
TextBox1.Text = dataReader.GetSqlString(3)
End While
End If
End Sub
Said that, please take notice, your code in the button click event is very dangerous because you concatenate whatever is typed by the user to a string that is then passed as a sql command to the database. This is the pattern used by the Sql Injection attacks that could destroy your database or stole valuable information from you tables

Memory leak - SQLCommand object?

Please have a look at the code below, which I have written as a test. It does not make the ASP.NET process grow too much:
Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Try
Dim Test As Integer
For Test = 0 To 1000000
Test1()
Next
Dim Test2 As String = "Test"
Catch ex As Exception
End Try
End Sub
Public Sub Test1()
Try
Dim objCommand As New SqlCommand
Dim strConString As String = "Data Source=IANSCOMPUTER;Initial Catalog=Test;Integrated Security=True"
Dim objCon As New SqlConnection
objCon.ConnectionString = strConString
objCon.Open()
objCommand.Connection = objCon
objCommand.CommandText = "select * from person "
Dim objDR As SqlDataReader = objCommand.ExecuteReader
If objDR.HasRows Then
Using objCon
End Using
End If
Catch ex As Exception
'I don't swallow exceptions.
End Try
End Sub
End Class
I am trying to detect a memory leak. I have found code similar to the above in the affected project. I notice that objCommand.dispose is not called. The project in question connects to an Oracle database and an SQL database. When connecting to an SQL database the above code is used. When connecting to an Oracle database Oracle.dataaccess.dll is used and the code looks different to reflect this.
My specific question is: if I avoid calling sqlcommand.dispose then will this cause a memory leak over time?
If a class has a Dispose method, that isn't getting called, then it is likely to be the source of a memory leak. Use Using, and it will call the Dispose method for you.
Your second example should look like the below, where all disposable object are wrapped in using blocks.
Dim strConString As String = "Data Source=IANSCOMPUTER;" +
"Initial Catalog=Test;Integrated Security=True"
Dim sqlStr as String = "select * from person "
Using objCon As New SqlConnection(strConString)
Using objCommand As New SqlCommand(sqlStr, objCon)
objCon.Open()
Using objDR As SqlDataReader = objCommand.ExecuteReader
If objDR.HasRows Then
End If
End Using
End Using
End Using

connect to SQL using asp.net

anyone can help me to connect to SQL server through vb.net using asp.net webform.. I have the database name Users and i want to use the database for the login page.. please help me..
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim ConnectionString As String
ConnectionString = ConfigurationSettings.AppSettings("ConnectionString")
Dim con As New SqlConnection(ConnectionString)
Dim cmd As New SqlCommand("Select UserId, Pwd from Users", con)
con.Open()
Dim myreader As SqlDataReader
myreader = cmd.ExecuteReader()
While myreader.Read()
If TxtUserId.Text = myreader("UserId").ToString().Trim()
AndAlso TxtPwd.Text = myreader("Pwd").ToString().Trim() Then
Session("UserId") = TxtUserId.Text
Response.Redirect("UserMyProfile.aspx")
Else
lblMsg.Visible = True
lblMsg.Text = "Inavalid UserId/Password"
End If
End While
con.Close()
End Sub
There's no shortage of tutorials on the web for this, but a good starting point is here.
EDIT: Based on your comments above, it sounds like you're not importing the Namespace you need for the ADO.NET data objects. Try adding this to the class file:
Imports System.Data.SqlClient

How to get work ASP.NET DataSet when connection losts?

I made a basic program that connects and gets content from a table via SQL, it's working normally. What I want is; when connection losts via SQL Server or internet connection, it must continue to list items that it got before connection losts instead of giving "Connection Problem Error".
Code is like this:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim strSQL As String
Dim conn As New SqlConnection
conn.ConnectionString = baglan()
conn.Open()
strSQL = "SELECT * FROM Telefon_Otomasyon"
Dim da As New SqlDataAdapter(strSQL, conn)
Dim dset As New DataSet()
da.Fill(dset, "Telefon_Otomasyon")
Dim Hepsi As DataRow
For Each Hepsi In dset.Tables("Telefon_Otomasyon").Rows
Response.Write(Hepsi("Arayan") & "<br />")
Next
End Sub
Thanks!
What you can do is store your dataset in Session: (excuse my VB, i'm very rusty with it)
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim strSQL As String
Dim conn As New SqlConnection
conn.ConnectionString = baglan()
conn.Open()
strSQL = "SELECT * FROM Telefon_Otomasyon"
Dim da As New SqlDataAdapter(strSQL, conn)
Dim dset As New DataSet()
Try
da.Fill(dset, "Telefon_Otomasyon")
MyDataset = dset
Catch ex As SqlException
dset = MyDataset
End Try
Dim Hepsi As DataRow
For Each Hepsi In dset.Tables("Telefon_Otomasyon").Rows
Response.Write(Hepsi("Arayan") & "<br />")
Next
End Sub
Private Property MyDataset() As DataSet
Get
return Session("myDataset")
End Get
Set(ByVal value as DataSet)
Session("myDataset") = value
End Set
End Property
This is also a very basic example, it needs to be tidied up before you can use it in production code, i.e. you need to consider what to do if there is no dataset stored in Session (if it returns null). You may want to be a bit smarter than that and just store a specific table. Note that Session can expire though, so do some reading on it. This should be enough to steer you in the right direction.
Further note: if you want something a little less volatile than Session then you could try using the Cache instead.
I'm not sure I understand the problem here. While I'm not a VB-programmer it seems to me like once the page loads it will run the SQL query and then process that dataset.
If you reload the page and the SQL connection isn't working you will get an error that you'd need to handle somehow (not sure how VB exceptions work but I'm sure you can figure that out).
If you on the other hand mean that you want to get whatever data you can from a query that gets disconnected mid-query - I'd say that is pretty hard and only relevant for huge queries.

Resources