ASPX VB.Net OleDb Insert Parameter into Query - asp.net

This is my first time writing in VB.Net for aspx pages.
The problem I having is that the parameter is not going into the query at the line for cmd.Parameters.Add.
The error I am getting is
No value given for one or more required parameters.
on the line
reader = cmd.ExecuteReader;
I have tried:
Adding the PARAMETERS at the top of the query like I have shown;
Removing and Adding [] around the parameter;
Changing OleDbType.Integer to OleDbType.SmallInt or OleDbType.BigInt
I know the query works as I can place it into MS Access and will run once I add the parameter. But not when I run it in Visual Studio.
Dim reader As OleDbDataReader
Dim cmd As OleDbCommand
Dim SQL As String = "PARAMETERS [#ID] Long; " &
"SELECT tblField.FieldName, " &
"tblField.FieldCaption, " &
"tblField.FieldMinCharNum, " &
"tblField.FieldMaxCharNum, " &
"tblField.FieldDefault, " &
"tblField.FieldSection, " &
"tblField.FirstQuestion, " &
"tblField.FieldDescription, " &
"tblField.FieldRegEx " &
"FROM tblField " &
"WHERE tblField.FieldID = [#ID];"
cmd = New OleDbCommand(SQL, Connection.Connection)
cmd.Parameters.Add("[#ID]", OleDbType.Integer).Value = ID
reader = cmd.ExecuteReader
I have a work around to make it work by just pre-inserting the parameter into the SQL string. But I want to make this work for other areas of the page that are yet to be written. Where user inputs are coming back into database so inputs are sanitised.

OLEDB doesn't use # to identify parameters. It uses ? and allocates parameters in the order they appear in the SQL amend your code to...
Dim reader As OleDbDataReader
Dim cmd As OleDbCommand
Dim SQL As String = "SELECT tblField.FieldName, " &
"tblField.FieldCaption, " &
"tblField.FieldMinCharNum, " &
"tblField.FieldMaxCharNum, " &
"tblField.FieldDefault, " &
"tblField.FieldSection, " &
"tblField.FirstQuestion, " &
"tblField.FieldDescription, " &
"tblField.FieldRegEx " &
"FROM tblField " &
"WHERE tblField.FieldID = ?"
cmd = New OleDbCommand(SQL, Connection.Connection)
cmd.Parameters.Add("?", OleDbType.Integer).Value = ID
reader = cmd.ExecuteReader

I don't understand why your mentioning SQL are you retrieving the data from SQL Query or are you going to insert data into the table.
your using Dim cmd As OleDbCommand means use to insert the input values into the database like see below sample code.
query = "INSERT INTO ds.students (ID,NAME,PIC)" & _
"VALUES (#ID,#NAME,#PIC);"
Dim cmd As OracleCommand = New OracleCommand(query, con)
cmd.Parameters.Add("#ID", Convert.ToInt32(TextBox1.Text))
cmd.Parameters.Add("#NAME", Convert.ToString(TextBox2.Text))
cmd.Parameters.Add("#PIC", arrImage)
con.Open()
cmd.ExecuteNonQuery()
con.Close()
you can try this also
Using cn As OracleConnection = New OracleConnection(connectionString)
cn.Open()
Using cmd As OracleCommand = New OracleCommand()
Const sql As String = "Insert into test_table (val1, val2) values (:var1, :var2)"
cmd.Connection = cn
cmd.Parameters.Add(New OracleParameter("var1", TxtField1.Text))
cmd.Parameters.Add(New OracleParameter("var2", TxtField2.Text))
cmd.CommandText = sql
cmd.ExecuteNonQuery()
End Using
End Using
if you want to insert the values into the database change your code according to given samples.
Hope this will help you.

Related

Invalid attempt to call Read when reader is closed even though the connection is open

I have encountered this "Invalid attempt to call Read when the reader is closed." error and I have tried to solve it for so many times. I think the connection is open but it still shows this error. Can somebody tell me why?
Here is the code:
Dim ConnComName As String
Dim sqlConnComName As SqlConnection
Dim sqlCmdComName As SqlCommand
Dim sqlComName As String
ConnComName = ConfigurationManager.ConnectionStrings("ConnString").ConnectionString
sqlComName = "Select COUNT(*) from TicketDetails where Company = '" & Company.SelectedValue & "' AND Priority = '" & Priority.SelectedValue & "' AND Application = '" & Application.SelectedValue & "' AND Creator = '" & Creator.Text & "' AND Status = '" & Status.SelectedValue & "' AND Module = '" & [Module].SelectedValue & "' AND Category = '" & Category.SelectedValue & "' AND IssueType = '" & IssueType.SelectedValue & "' AND IssueDescription = '" & IssueDescription.Text & "' "
sqlConnComName = New SqlConnection(ConnComName)
sqlConnComName.Open()
sqlCmdComName = New SqlCommand(sqlComName, sqlConnComName)
Dim sqlReader_ComName As SqlDataReader = sqlCmdComName.ExecuteReader()
While sqlReader_ComName.Read()
If sqlReader_ComName.GetValue(0) < 1 Then
ElseIf sqlReader_ComName.GetValue(0) > 0 Then
Dim CompanyName As String
Dim ConnComName01 As String
Dim sqlConnComName01 As SqlConnection
Dim sqlCmdComName01 As SqlCommand
Dim sqlComName01 As String
ConnComName01 = ConfigurationManager.ConnectionStrings("ConnString").ConnectionString
sqlComName01 = "Select Company from TicketDetails Where Company = '" & Company.SelectedValue & "' AND Priority = '" & Priority.SelectedValue & "' AND Application = '" & Application.SelectedValue & "' AND Creator = '" & Creator.Text & "' AND Status = '" & Status.SelectedValue & "' AND Module = '" & [Module].SelectedValue & "' AND Category = '" & Category.SelectedValue & "' AND IssueType = '" & IssueType.SelectedValue & "' AND IssueDescription = '" & IssueDescription.Text & "' "
sqlConnComName01 = New SqlConnection(ConnComName01)
sqlConnComName01.Open()
sqlCmdComName01 = New SqlCommand(sqlComName01, sqlConnComName01)
Dim sqlReader_ComName01 As SqlDataReader = sqlCmdComName01.ExecuteReader()
While sqlReader_ComName01.Read()
CompanyName = sqlReader_ComName01.GetValue(0)
' end while ComName01
End While
sqlReader_ComName01.Close()
sqlCmdComName01.Dispose()
sqlConnComName.Close()
End If
End While
sqlReader_ComName.Close()
sqlCmdComName.Dispose()
sqlConnComName.Close()
As has been said in the comments, the reason you are getting the error is because you are using a shared SqlConnection, which you close at the end of your inner loop, although there is actually no good reason to share a connection object here; .NET uses connection pooling behind the scenes, so there is little or no downside to creating new connection objects for every command, and it can often save confusion like this. You should also use Using blocks to ensure that all your managed resources are disposed of correctly and at the right time. Finally, and I can't stress this enough, use Parameterised queries, your code is vulnerable to injection, malformed SQL, type errors and will be unable to make use of query plan caching.
Although you have two loops in your code, all you ever do in those loops is to assign a value to a string:
While sqlReader_ComName01.Read()
CompanyName = sqlReader_ComName01.GetValue(0)
End While
So with every inner and outer loop, you overwrite the previous value, making all loops other than the last completely pointless. Since your SQL has no order by, you also have no idea which order the results will come in, so the "last" record could be any record here.
You don't need two loops here, if you only want a single value from the database, just select single value, there is no point returning 500 records if you are only going to use one.
So with all these changes your code might look something like this (forgive any syntax errors, it is about 8 years since I last wrote any VB.net)
Dim CompanyName As String
'Change SQL to only select 1 record, use an order by, and use parameters
Dim sql As String = "Select TOP (1) Company from TicketDetails Where Company = #Company AND Priority = #Prioirty AND Application = #Application AND Creator = #Creator AND Status = #Status AND Module = #Module AND Category = #Category AND IssueType = #IssueType AND IssueDescription = #IssueDescription ORDER BY Company"
' Create new conneciton in Using block
Using connection As SqlConnection = New SqlConnection(ConfigurationManager.ConnectionStrings("ConnString").ConnectionString)
'Create new command in using block
Using command As SqlCommand = New SqlCommand(sql, connection)
'Add parameters to command, change your data types and lengths as necessary
command.Parameters.Add("#Company", SqlDbType.VarChar, 50).Value = Company.SelectedValue
command.Parameters.Add("#Priority", SqlDbType.VarChar, 50).Value = Priority.SelectedValue
command.Parameters.Add("#Application", SqlDbType.VarChar, 50).Value = Application.SelectedValue
command.Parameters.Add("#Creator", SqlDbType.VarChar, 50).Value = Creator.Text
command.Parameters.Add("#Status", SqlDbType.VarChar, 50).Value = Status.SelectedValue
command.Parameters.Add("#Module", SqlDbType.VarChar, 50).Value = [Module ].SelectedValue
command.Parameters.Add("#Category", SqlDbType.VarChar, 50).Value = Category.SelectedValue
command.Parameters.Add("#IssueType", SqlDbType.VarChar, 50).Value = IssueType.SelectedValue
command.Parameters.Add("#IssueDescription", SqlDbType.VarChar, 50).Value = IssueDescription.Text
'Open the connection
connection.Open()
'Create the data reader
Using reader As SqlDataReader = command.ExecuteReader()
'If the reader.Read() method returns true, then there is a record, so read it and assign it to the variable
If reader.Read()
CompanyName = reader.GetString(0);
End If
End Using
End Using
End Using

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.

second ExecuteReader() doesn't work

I have a code which checks the validity of user and then, if a user is valid it inserts certain values in the database.
My problem is when After I query my database to check if a user is valid and after that i try to pass the additional value to its account the flow stops when I invoke ExecuteReader() for the second time.
There is no error, or anything like that. I tried to substitute ExecuteReader() with ExecuteNoneQuery but still it's not working. I tried all the query in mysql command prompt they are working perfectly. I really can't understand what am I doing wrong there. Can anyone help me please?
Here is the code:
Try
myconn.Open()
Dim stquery As String = "SELECT * from accountstbl WHERE SE_ID = " & Id.Text
Dim smd = New MySqlCommand(stquery, myconn)
Dim myreader = smd.ExecuteReader()
If Not myreader.HasRows Then
errorUser.Visible = True
Else
myreader.Read()
Dim name As String = myreader.Item("user_name").ToString()
Dim stquery2 = "INSERT into backup VALUES (" & name & ", '" & Info & "')"
Dim smd2 = New MySqlCommand(stquery2, myconn)
Dim Myreader2 As MySqlDataReader
'smd.ExecuteNonQuery()'
'THE CODE STOPS HERE'
Myreader2 = smd2.ExecuteReader()
'Myreader2.Read()'
MsgBox("The BACKUP INFORMATION HAS BEEN SAVED")
End If
myconn.Close()
Catch ex As Exception
Dim ErrorMessage As String = "alert('" & ex.Message.ToString() & "');"
Page.ClientScript.RegisterStartupScript(Me.GetType(), "ErrorAlert", ErrorMessage, True)
myconn.Close()
End Try
Because your second query is an update, not a select, you need to execute it using the ExecuteNonQuery method. Your commented-out code shows an attempt to call ExecuteNonQuery but on the wrong command object (smd when it should be smd2). Try something like this instead:
myreader.Read()
Dim name As String = myreader.Item("user_name").ToString()
Dim stquery2 = "INSERT into backup VALUES (" & name & ", '" & Info & "')"
Dim smd2 = New MySqlCommand(stquery2, myconn)
smd2.ExecuteNonQuery()
The ExecuteNonQuery method returns the number of rows updated as an int value, so you can capture it if it's valuable to you. In your case it's probably not, but here's how you'd check anyway:
int rowsAdded = smd2.ExecuteNonQuery();
if (rowsAdded == 1) {
// expected this
} else {
// didn't expect this
}
Finally, concatenating strings to build SQL commands can leave you vulnerable to SQL Injection attacks. Please take a look at using parameterized queries. There's a decent example here.
If you want to execute nested Reader, you have to create another connection. You need somethig like
smd2 = New MySqlCommand(stquery2, myconn2)' myconn2 is another connection
OR
Set "MultipleActiveResultSets=True in your connection string.
Also, use ExecuteNonQuery() for Inserting
Dim name As String = myreader("user_name").ToString()
Dim stquery2 = "INSERT into backup VALUES ('" & name & "', '" & Info & "')"
Dim smd2 = New MySqlCommand(stquery2, myconn)
smd.ExecuteNonQuery()
Please use Parameterized query to avoid SQL Injection
The logic is that you need to close your first reader (myreader) before executing another reader (MyReader2) on the same connection.

uploading image with extension not working

i am trying to upload an image and saving image name in database as the session name with extension .jpg
i got problem that only the image name saved in database not the extension. i am using this code
Dim strPath As String = Server.MapPath("~/UserPics/")
If AsyncFileUpload1.HasFile Then
AsyncFileUpload1.SaveAs(strPath & Session("UserName").ToString() & ".jpg")
lblUploadMessage.Text = "You uploaded " + AsyncFileUpload1.FileName
con.Open()
Dim objCmd As New SqlCommand("insert into regist( image1) values ('" & Session("UserName").ToString() & "')", con)
objCmd.ExecuteNonQuery()
con.Close()
Else
lblUploadMessage.Text = "Please select an image first"
Return
End If
You are not inserting the same string you are saving, you have to add the extension see below. Also, add the extension from the file posted instead of hard-coding:
Dim objCmd As New SqlCommand("insert into regist(image1) values ('" & _
Session("UserName").ToString() & _
System.IO.Path.GetExtension(AsyncFileUpload1.PostedFile.FileName) & "')", con)
Please change you code to using parameters in order to prevent SQL Injection attacks:
Dim objCmd As New SqlCommand(con)
Dim sql As String = "insert into regist(image1) values (#image)"
Dim param(1) As SqlParameter
param(0) = New SqlParameter("#image", SqlDbType.VarChar)
param(0).Value = Session("UserName").ToString() & _
System.IO.Path.GetExtension(AsyncFileUpload1.PostedFile.FileName);
objCmd.Parameters.AddRange(param)
objCmd.ExecuteNonQuery()
con.Close()
Change
Dim objCmd As New SqlCommand("insert into regist( image1) values ('" & Session("UserName").ToString() & "')", con)
to
Dim objCmd As New SqlCommand("insert into regist( image1) values ('" & Session("UserName").ToString() & ".jpg" & "')", con)

Writing an update query in asp.net (access database) (visual basic)

I have this code:
Dim pathString As String = HttpContext.Current.Request.MapPath("Banking.mdb")
Dim odbconBanking As New OleDbConnection _
("Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Data Source=" + pathString)
Dim sql As String
sql = "UPDATE tblAccounts balance = " & CDbl(balance + value) & " WHERE(accountID = " & accountID & ")"
odbconBanking.Open()
Dim cmd As New OleDbCommand(sql, odbconBanking)
cmd.ExecuteNonQuery()
However, an exception is thrown, when I run it:
Syntax error in UPDATE statement.
I tried to run a similar statement in Access and it works fine.
I think the missing is SET.
Try: UPDATE table SET field = newvalue WHERE criteria;
Just modify:
sql = "UPDATE tblAccounts SET balance = " & CDbl(balance + value) & " WHERE(accountID = " & accountID & ")"
http://office.microsoft.com/en-us/access/HA100765271033.aspx
The SQL Statement definitely is missing the SET keyword. Also, I suggest you to brush up on parameterized query:
Dim sql As String = "UPDATE tblAccounts " & _
"SET balance = ? " & _
"WHERE(accountID = ?)"
Dim cmd As New OleDbCommand(sql, odbconBanking)
cmd.Parameters.Add("Balance", CDbl(balance + value))
cmd.Parameters.Add("AccountId", accountID
cmd.ExecuteNonQuery()
This way, not only is the SQL Statment is clearer, it help prevents possible SQL injection attacks.
You are missing SET as part of UPDATE.
It should be UPDATE tablename SET fieldname = ... WHERE [criteria].
On a side note, you are using classic asp style code inside asp.net. I will suggest reading some docs on ASP.net and how to design applications in a layered manner.
A good start is here: Enterprise Library's Data Access Application Block
Link: https://web.archive.org/web/20210612110113/https://aspnet.4guysfromrolla.com/articles/030905-1.aspx

Resources