asp.net database sessions are not being cleared - asp.net

I am Connecting with oracle database in asp.net using sqldatasource and here is my connection string
<add name="ConnectionString3" connectionString="Data Source=sml; User ID=sml; Password=sml; Unicode=True; Pooling=False;" providerName="System.Data.OracleClient"/>
I Open the Connection and after doing select something i do close the connection.Problem is that when i browse the session of Database then there two locked sessions exist there . and they don't clear till i shutdown the asp.net server.can Any one guide me what is the proper way in asp.net to connect with oracle db and then manage the connections to clear after connecting with database.I meant how i can logout from database after querying from.
update
Dim con = New OleDbConnection("Data Source=sml; User ID=sml; Password=sml; provider=OraOLEDB.Oracle; Pooling=false")
Try
con.Open()
Dim cmd As New OleDbCommand("SELECT UPDTIME, YBAL_J, SCROLL_J, PENDING_PMT_J, YBAL_B, SCROLL_B, PENDING_PMT_B, CR_DT, OUT_BAL_J, OUT_BAL_B,SUGAR_J,CANE_CRUSH_J,RECOVERY_J,ETHANOL_J,SHEET_J,SUGAR_B,CANE_CRUSH_B,RECOVERY_B,ETHANOL_B FROM CMS20122013.V_DASH_LABELS#CMS", con)
Dim da As New OleDbDataAdapter(cmd)
Dim ds As New DataSet
da.Fill(ds)
Label1.Text = ds.Tables(0).Rows(0)(0).ToString
Label5.Text = ds.Tables(0).Rows(0)(0).ToString
Label2.Text = ds.Tables(0).Rows(0)(1).ToString
Label3.Text = "Scroll Issued: " & ds.Tables(0).Rows(0)(2).ToString
Label4.Text = "Payment Pending: " & ds.Tables(0).Rows(0)(3).ToString
Label6.Text = ds.Tables(0).Rows(0)(4).ToString
Label7.Text = "Scroll Issued: " & ds.Tables(0).Rows(0)(5).ToString
Label8.Text = "Payment Pending: " & ds.Tables(0).Rows(0)(6).ToString
Label14.Text = ds.Tables(0).Rows(0)(7).ToString
GridView4.Columns(4).HeaderText = ds.Tables(0).Rows(0)(8).ToString
GridView9.Columns(4).HeaderText = ds.Tables(0).Rows(0)(9).ToString
GridView2.Columns(0).HeaderText = "Crushing [" & ds.Tables(0).Rows(0)(11).ToString & "]"
GridView7.Columns(0).HeaderText = "Crushing [" & ds.Tables(0).Rows(0)(16).ToString & "]"
con.Close()
con.Dispose()
Catch ex As Exception
con.Close()
con.Dispose()
Finally
con.Close()
con.Dispose()
End Try

Have you tried the c# "using" syntax?
using(var connection = new OracleConnection("some connection string"))
{
connection.Open();
//do stuff with connection
}
More details here: http://msdn.microsoft.com/en-us/library/yh598w02(v=vs.100).aspx

Related

getting data from database asp.net

i am trying to get data from ms access database using this code but i can not this is my code is this correct
Dim query As String = "SELECT [data] FROM tabless WHERE user = '" & user.Text & "'"
Using connection As New OleDbConnection(connectionString)
Dim cmd As New OleDbCommand(query)
Dim adapter As OleDbDataAdapter = New OleDbDataAdapter(query, connection)
Dim com As New OleDbCommand(query, connection)
connection.Open()
'on the line below I get an error: connection property has not been initialized
Dim reader As OleDbDataReader = cmd.ExecuteReader()
While reader.Read()
Label1.Text = (reader(0).ToString())
End While
reader.Close()
End Using
Database
|data|
asl
trying to get data from database and trying to show it in a label is this possible
You never associated cmd with the connection, and you never use com or adapter. This is the sort of thing you can figure out by stepping through your code line by line and inspecting the state of it.
Dim query As String = "SELECT [data] FROM tabless WHERE user = '" & user.Text & "'"
Using connection As New OleDbConnection(connectionString)
Dim cmd As New OleDbCommand(query, connection)
connection.Open()
Dim reader As OleDbDataReader = cmd.ExecuteReader()
While reader.Read()
Label1.Text = (reader(0).ToString())
End While
reader.Close()
End Using
Also, your code is vulnerable to a SQL Injection Attack. You should not be concatenating strings together to form your queries. You should instead use parameterized queries.

connection string data source error

in an aspx.vb file
Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
Dim con As New OleDbConnection("Provider= SQLOLEDB.1;Integrated Security=true; data source=myserver; ")
Dim cmd As New OleDbCommand
cmd.Connection = con
cmd.CommandText = "Insert into demo.dbo.masters1 values ('" & TextBox1.Text & " ," & TextBox4.Text & " , " & TextBox3.Text & " ')"
con.Open()
If (cmd.ExecuteNonQuery() > 0) Then
Label1.BorderColor = Drawing.Color.Aquamarine
Else
Label1.BorderColor = Drawing.Color.Black
End If
con.Close()
End Sub
I am using Windows Authentication.
The server is up and running.
I've also tried:
Dim con As New OleDbConnection("Provider= SQLOLEDB.1;Integrated Security=true; data source=C:\Program Files\Microsoft SQL Server\MSSQL10_50.MSSQLSERVER\MSSQL\DATA\database_name.mdf; ")
However, I'm getting the following error:
No error message available, result code: DB_E_ERRORSOCCURRED(0x80040E21).
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.Data.OleDb.OleDbException: No error message available, result code: DB_E_ERRORSOCCURRED(0x80040E21).
Look like you are using OleDbConnection for SQL Server.
You want to SqlConnection if you use SQL Server. For example,
using(var con = new SqlConnection(
"Server=myServerAddress;Database=myDataBase;Trusted_Connection=True;"))
{
var query = "insert statement ...";
using(var cmd = new SqlCommand(query, con)){
cmd.CommandType = CommandType.Text;
con.Open();
....
}
}
You might want to look at the connection string format here too.
FYI: Use the parameterize query to avoid SQL Injection attack.

asp.net.vb Invalid attempt to read when no data is present

I am not sure why this code doesn't work
I have follow according to the table field data and it I am still unable to get the SQL Datareader to work. I have checked the tables and all datafields, everything is correct. But I still am unable to read data from the database. Help T.T
Dim connectionString = ConfigurationManager.ConnectionStrings("CleanOneConnectionString").ConnectionString
Dim myConn As New SqlConnection(connectionString)
myConn.Open()
Dim cmd = "Select * from [Member] where Email = #Email"
Dim myCmd As New SqlCommand(cmd, myConn)
myCmd.Parameters.AddWithValue("#Email", emailBox.Text)
Dim objReader As SqlDataReader
objReader = myCmd.ExecuteReader()
objReader.Read()
Result.Text = " " 'initialise label to show correct message for available or found
'Check the reader see if any record found matching WHERE
If (objReader.Read()) Then
'read=true, check Password
'Dim tpassword As String = objReader.GetString(5)
'If tpassword = passwordBox.Text Then
'Result.Text = "** Login Succcessful **"
Result.Text = objReader.GetString(1)
'Else
'Result.Text = "Invalid Password" & objReader.GetString(5) & passwordBox.Text
'End If
'reader=false, no such records matching WHERE
Else
Result.Text = objReader.GetString(1)
End If
myCmd.Dispose()
myConn.Dispose()
Testing with MySql: I get an error that the SQL syntax is not correct.
I then removed the [ ] and it works.
How is that with SqlServer? Try at least, i'd say.

SQL error: "Incorrect syntax near AND"

"[..] security info=False;initial catalog=pooja2011"
Dim cmd As New Data.SqlClient.SqlCommand
Dim con As New Data.SqlClient.SqlConnection(constr)
Try
Dim strSql As String = "UPDATE a1_ticket SET BANK = '" & Literal20.Text & "' AND PAID = '" & Label1.Text & "'AND BID = '" & Literal21.Text & "' WHERE Ticket_no ='" & Literal3.Text & "'"
'------------"
con.Open()
cmd.Connection = con
cmd.CommandText = strSql
cmd.ExecuteNonQuery()
Catch ex As Exception
Response.Write(ex.Message)
Finally
cmd.Dispose()
con.Dispose()
End Try
ERROR : Incorrect syntax near AND
You are not using parametrized queries and thus making your code vulnerable to SQL injection. Here's how to improve it:
Try
Using conn = New SqlConnection(constr)
Using cmd = conn.CreateCommand()
conn.Open()
Dim sql As String = "UPDATE a1_ticket SET BANK = #bank, PAID = #paid, BID = #bid WHERE Ticket_no = #ticketNo"
cmd.CommandText = sql
cmd.Parameters.AddWithValue("#bank", Literal20.Text)
cmd.Parameters.AddWithValue("#paid", Label1.Text)
cmd.Parameters.AddWithValue("#bid", Literal21.Text)
cmd.Parameters.AddWithValue("#ticketNo", Literal3.Text)
cmd.ExecuteNonQuery()
End Using
End Using
Catch ex As Exception
Response.Write(ex.Message)
End Try
Well, the AND doesn't have a space after the single quote:
Label1.Text & "'AND BID = '"
should probably be:
Label1.Text & "' AND BID = '"
If this doesn't resolve your issue, can you post your error message?

oRecordset in ASP.NET mySQL

I have this mySQL code that connects to my server. It connects just fine:
Dim MyConString As String = "DRIVER={MySQL ODBC 3.51 Driver};" & _
"SERVER=example.com;" & _
"DATABASE=xxx;" & _
"UID=xxx;" & _
"PASSWORD=xxx;" & _
"OPTION=3;"
Dim conn As OdbcConnection = New OdbcConnection(MyConString)
conn.Open()
Dim MyCommand As New OdbcCommand
MyCommand.Connection = conn
MyCommand.CommandText = "select * from userinfo WHERE emailAddress = '" & theUN & "'""
MyCommand.ExecuteNonQuery()
conn.Close()
However, i have an old Classic ASP page that uses "oRecordset" to get the data from the mySQL server:
Set oConnection = Server.CreateObject("ADODB.Connection")
Set oRecordset = Server.CreateObject("ADODB.Recordset")
oConnection.Open "DRIVER={MySQL ODBC 3.51 Driver}; SERVER=example.com; PORT=3306; DATABASE=xxx; USER=xxx; PASSWORD=xxx; OPTION=3;"
sqltemp = "select * from userinfo WHERE emailAddress = '" & theUN & "'"
oRecordset.Open sqltemp, oConnection,3,3
And i can use oRecordset as follows:
if oRecordset.EOF then....
or
strValue = oRecordset("Table_Name").value
or
oRecordset("Table_Name").value = "New Value"
oRecordset.update
etc...
However, for the life of me, i can not find any .net code that is similar to that of my Classic ASP page!!!!!
Any help would be great! :o)
David
This is what you have to do:
instead of MyCommand.ExecuteNonQuery you should use MyCommand.ExecuteQuery and assign it to DataReader.
Check out this sample:
Dim myConnection As SqlConnection
Dim myCommand As SqlCommand
Dim dr As New SqlDataReader()
'declaring the objects
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs)_
Handles MyBase.Load
myConnection = New SqlConnection("server=localhost;uid=sa;pwd=;database=pubs")
'establishing connection. you need to provide password for sql server
Try
myConnection.Open()
'opening the connection
myCommand = New SqlCommand("Select * from discounts", myConnection)
'executing the command and assigning it to connection
dr = myCommand.ExecuteReader()
While dr.Read()
'reading from the datareader
MessageBox.Show("discounttype" & dr(0).ToString())
MessageBox.Show("stor_id" & dr(1).ToString())
MessageBox.Show("lowqty" & dr(2).ToString())
MessageBox.Show("highqty" & dr(3).ToString())
MessageBox.Show("discount" & dr(4).ToString())
'displaying the data from the table
End While
dr.Close()
myConnection.Close()
Catch e As Exception
End Try
HTH
Dim conn As OdbcConnection = New OdbcConnection("DRIVER={MySQL ODBC 3.51 Driver}; SERVER=xxx.com; DATABASE=xxx; UID=xxx; PASSWORD=xxx; OPTION=3;")
conn.Open()
Dim MyCommand As New OdbcCommand
MyCommand.Connection = conn
MyCommand.CommandText = "SELECT * FROM userinfo"
Dim rst = MyCommand.ExecuteReader()
While rst.Read()
response.write(rst("userID").ToString())
End While
conn.Close()
Dim email As String = "anyone#anywhere.com"
Dim stringValue As String
Using conn As OdbcConnection = New OdbcConnection(MyConString)
conn.Open()
Dim sql = "Select ... From userInfo Where emailAddress = #Email"
Using cmd As OdbcCommand = New OdbcCommand(sql, conn)
cmd.Parameters.AddWithValue("#Email", email)
Dim reader As OdbcDataReader = cmd.ExecuteReader()
While reader.Read()
stringValue = reader.GetString(0)
End While
End Using
conn.Close()
End Using
'To do an Update
Using conn As OdbcConnection = New OdbcConnection(MyConString)
conn.Open()
Dim sql As String = "Update userInfo Set Column = #Value Where PK = #PK"
Using cmd As OdbcCommand = New OdbcCommand(sql, conn)
cmd.Parameters.AddWithValue("#Email", email)
cmd.ExecuteNonQuery()
End Using
End Using
'To do an Insert
Using conn As OdbcConnection = New OdbcConnection(MyConString)
conn.Open()
Dim sql As String = "Insert userInfo(Col1,Col2,...) Values(#Value1,#Value2...)"
Using cmd As OdbcCommand = New OdbcCommand(sql, conn)
cmd.Parameters.AddWithValue("#Col1", value1)
cmd.Parameters.AddWithValue("#Col2", value2)
...
cmd.ExecuteNonQuery()
End Using
End Using
First, even in ASP Classic, it is an absolutely horrid approach to concatenate a value directly into a SQL statement. This is how SQL Injection vulnerabilities happen. You should always sanitize values that get concatenated into SQL statements. In .NET, you can use parametrized queries where you replace the values that go into your query with a variable that begins with an # sign. You then add a parameter to the command object and set your value that way. The Command object will sanitize the value for you.
ADDITION
You mentioned in a comment that your ASP Classic code is shorter. In fact, the .NET code is shorter because there are a host of things happening that you do not see and have not implemented in your ASP Classic code. I already mentioned one which is sanitizing the inputs. Another is logging. Out of the box, if an exception is thrown, it will log it in the Event Log with a call stack. To even get a call stack in ASP Classic is a chore much less any sort of decent logging. You would need to set On Error Resume Next and check for err.number <> 0 after each line. In addition, without On Error Resume Next, if an error is thrown, you have no guarantee that the connection will be closed. It should be closed, but the only way to know for sure is to use On Error Resume Next and try to close it.
Generally, I encapsulate all of my data access code into a set of methods so that I can simply pass the SQL statement and the parameter values and ensure that it is called properly each time. (This holds true for ASP Classic too).

Resources