SQL error: "Incorrect syntax near AND" - asp.net

"[..] 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?

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

Why i get error "Syntax error in query expression"

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 & "'"

Update statement error during command execution

Dim iReturn As Boolean
Using SQLConnection As New MySqlConnection(strMySqlConnectionString)
Using sqlCommand As New MySqlCommand
With sqlCommand
.CommandText = "UPDATE user" & "SET FirstName = #FirstName" & "From user" & "WHERE Username = #Username;"
.Connection = SQLConnection
.CommandType = CommandType.Text '// You missed this line
.Parameters.AddWithValue("#FirstName", editFirsName.Text)
.Parameters.AddWithValue("#Username", editusername.Text)
End With
Try
SQLConnection.Open()
sqlCommand.ExecuteNonQuery()
iReturn = True
MsgBox("User Was Update succesfully")
Catch ex As MySqlException
MsgBox(ex.Message.ToString)
iReturn = False
Finally
SQLConnection.Close()
End Try
End Using
End Using
If iReturn = False Then
End If
I am getting the following error from the code above:
Fatal Error Encountered during command execution.
Your SQL update syntax appears incorrect.
Change:
.CommandText = "UPDATE user" & "SET FirstName = #FirstName" & "From user" & "WHERE Username = #Username;"
To
.CommandText = "UPDATE user SET FirstName = #FirstName WHERE Username = #Username;"

asp.net database sessions are not being cleared

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

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)

Resources