Why i get error "Syntax error in query expression" - ms-access-2010

I got error i like this "SYNTAX ERROR IN QUERY EXPRESSION _Name= ' ' "
Help me please . what's wrong with my code ?
Try
Connection.Open()
Dim query As String
query = ("SELECT * from RegistrationTable WHERE _Name = '" & ListBox1.Text & "'")
command = New OleDbCommand(query, Connection)
Reader = command.ExecuteScalar
While Reader.Read
txtPID.Text = Reader("PatientID")
txtName.Text = Reader("_Name")
txtAge.Text = Reader("_Age")
cmbGender.Text = Reader("_Gender")
End While
Connection.Close()
Catch ex As Exception
MsgBox(ex.Message)
Finally
Connection.Dispose()
End Try

That underscore means that you need square brackets:
"SELECT * from RegistrationTable WHERE [_Name] = '" & ListBox1.Text & "'"

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

insert into syntax error

Private databaseConnector As DatabaseConnector
Dim fulltxtSQL As String
DatabaseConnector = New DatabaseConnector
Try
fulltxtSQL = "insert into [user-table] (username, password) VALUES ('" & UserName.Text & "','" & Password.Text & "')"
DatabaseConnector.RunSqlNonQuery(fulltxtSQL)
If DatabaseConnector.RunSqlNonQuery(fulltxtSQL) = True Then
MsgBox("thank you for registering ", vbInformation, Title.Trim)
Response.Redirect("Default.aspx")
Exit Sub
Else
MsgBox(MsgBox("There has been a error in your registering", vbInformation, Title.Trim))
End If
Catch ex As Exception
MsgBox(ex.Message.Trim, MsgBoxStyle.Information + MsgBoxStyle.OkOnly, Me.Title.Trim)
Exit Sub
End Try
End Sub
am trying to get the data from textbox to the database table.
syntax error in insert into statement the connection to the database works fine but when it reaches the insert into statement i get the error
Try this
INSERT INTO [user-table] ([username],[password]) VALUES('" & UserName.Text & "','" & Password.Text & "')"
You query contains special character such as user,table and password so it will give error. So what you need to do is to put such characters in paranthesis [].
Also you should use parameterized query.
try using this command
cmd = New System.Data.OleDb.OleDbCommand("INSERT INTO [user-table] ([username],[password]) VALUES('" & UserName.Text & "','" & Password.Text & "')", con)
if your table name contains such special charaters then use square brackets.

No data exists for row/column

While executing the following code in ASP.NET with VB, I am getting the error "No data exists for the row/column."
Dim hdnuserid = e.CommandArgument
If e.CommandName = "additem" Then
' First, see if the product is already in the vendor_catalog table
Dim dr, dr2, username
dr = connection.returnsqlresult("SELECT * FROM vendor_users where vendor_id = '" & Request("vendor_id") & "' AND userid = '" & hdnuserid & "'")
If dr.hasrows() Then
dr.read()
Response.Write("<script type=""text/javascript"">alert(""User already assigned to this vendor."");</script>")
Else
dr2 = connection.returnsqlresult("SELECT * FROM users WHERE userid = '" & hdnuserid & "'")
Response.Write(hdnuserid)
If dr2.hasrows() Then
dr2.read()
username = dr("username")
connection.executesql("INSERT INTO vendor_users(userid, vendor_id, username) VALUES('" & hdnuserid & "','" & Request("vendor_id") & "','" & username & "')")
'ScriptManager.RegisterStartupScript(Me, GetType(Page), "itemsadded", "window.opener.__doPostBack('__Page', 'populate_usergrid');window.close();", True)
Else
Response.Write("<script type=""text/javascript"">alert(""User does not exist."");</script>")
End If
dr2.close()
End If
dr.close()
Else
End If
I have checked that the columns exist in my tables, and also checked the select * from users statement in SQL directly with a hard coded value and I see the result I expect. I'm not sure why I am getting this error. The error is being thrown on the username = dr("username") line.
Any assistance in this would be very helpful.
JV
I think you have a bit of a typo. Change
username = dr("username")
to
username = dr2("username")
Shouldnt the reader object be dr2 instead of dr? since dr doesnt have any rows, dr("username") wouldnt be accessible.
username = dr2("username")

How to check if mysql query returns nothing?

I'm writing a project and at the some point i have to check if there is an entry in database which matches the content of id-textbox and password-textbox. But I don't know how to indicate in my backend code(VB) that the query returns nothing.
This is the code I am using. But it doesn't work somehow. Error messages Are not being prompt:
Try
myconn.Open()
Dim stquery As String = "SELECT * from accountstbl WHERE user_ID = " & IdNumb.Text
Dim smd As MySqlCommand
Dim myreader As MySqlDataReader
smd = New MySqlCommand(stquery, myconn)
myreader = smd.ExecuteReader()
If myreader.Read() = True Then
If myreader.Item("user_ID") = IdNumb.Text Then
If myreader.Item("password") = CurrPass.Text Then
'some code if the user input is valid
Else
errorPassID.Visible = True
End If
Else
errorPassC.Visible = True
End If
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
Will appreciate any help or suggestion.
I will try to check if the reader return rows and if not, emit an error message.
Also, do not use string concatenation to build queries, use always parametrized queries
myconn.Open()
Dim stquery As String = "SELECT * from accountstbl WHERE user_ID = #id"
Dim smd = New MySqlCommand(stquery, myconn)
smd.Parameters.AddWithValue("#id", Convert.ToInt32(IdNumb.Text))
Dim myreader = smd.ExecuteReader()
if Not myreader.HasRows Then
Dim ErrorMessage As String = "alert('No user found');"
Page.ClientScript.RegisterStartupScript(Me.GetType(), "ErrorAlert", ErrorMessage, True)
myconn.Close()
return
else
myreder.Read()
' no need to check if id is equal, you pass it as parameter to a where clause'
If myreader.Item("password") = CurrPass.Text Then
'some code if the user input is valid '
Else
errorPassID.Visible = True
' or error message '
End If
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
Note also that passing a clear text password along the wire is a serious security hole. I hope you have stored an hash of the password and check on that instead.
By the way, why don't pass also the password hash in the query? Somthing like this:
Dim stquery As String = "SELECT * from accountstbl WHERE user_ID = #id AND password = #pwd"
In this way, if you have a record returned the user is validated and your client side code will be simple

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?

Resources