Update statement error during command execution - asp.net

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;"

Related

Procedure expects #location parameter which was not supplied. It is driving me nuts

I know this thread will probably get flagged as duplicate but I have reviewed all similar posts but none seems to help resolve this issue:
I have this code snip:
Dim loc As String = DirectCast(GridView1 _
.FooterRow.FindControl("txtLocation"), TextBox).Text
cmd.CommandText = "insert into Locations(Location " & _
") values(#Location);" & _
"select LocationID, Location from locations"
cmd.Parameters.AddWithValue("#Location", SqlDbType.VarChar).Value = loc
Just to keeping it simple.
This works great.
Then I turned this inline code into stored procedure:
ALTER PROCEDURE [dbo].[spx_AddNewLoc]
#Location varchar(150)
AS
set nocount on
BEGIN --add new request type
INSERT INTO Locations(Location)VALUES(#Location)
SELECT LocationID, Location from locations
END
set nocount off
Then called it in my codefile:
Dim loc As String = DirectCast(GridView1 _
.FooterRow.FindControl("txtLocation"), TextBox).Text
cmd.CommandText = "spx_AddNewLoc "
cmd.Parameters.AddWithValue("#Location", SqlDbType.VarChar).Value = loc
I just keep getting "Procedure expects #location which was not supplied."
Any ideas what I am missing?
<FooterTemplate>
    <asp:TextBox ID="txtlocation" runat="server" placeholder="Please enter location here..." style="width:400px;"></asp:TextBox><br />
</FooterTemplate>
<FooterTemplate>
<asp:Button ID="btnAdd" runat="server" Text="Add" OnClick = "AddNewLocation" />
</FooterTemplate>
'//** latest code below
Protected Sub AddNewLocation(ByVal sender As Object, ByVal e As EventArgs)
Dim IsAdded As Boolean = True
Dim loc As String = DirectCast(GridView1 _
.FooterRow.FindControl("txtLocation"), TextBox).Text
Dim con As New SqlConnection(strConnString)
Dim cmd As New SqlCommand()
cmd.CommandType = CommandType.Text
cmd.CommandText = "insert into Locations(Location " & _
") values(#Location);" & _
"select LocationID, Location from locations"
cmd.Parameters.Add("#Location", SqlDbType.VarChar).Value = loc
If IsAdded = True Then
lblMsg.Text = (Convert.ToString("'") & loc) + "' location added successfully!"
lblMsg.ForeColor = System.Drawing.Color.Green
Else
lblMsg.Text = (Convert.ToString("Error while adding '") & loc) + "' locaton!"
lblMsg.ForeColor = System.Drawing.Color.Red
End If
GridView1.DataSource = GetData(cmd)
GridView1.DataBind()
End Sub
The reason for the error is because you have not set the CommandType to use CommandType.StoredProcedure. I have mocked up both examples to highlight this error.
This is the code prior to me setting the CommandType:
This is the code once I had set the CommandType:
This is the working code:
Using con As New SqlConnection(strConnString),
cmd As New SqlCommand With {.CommandText = "spx_AddNewLoc", .CommandType = CommandType.StoredProcedure,
.Connection = con}
cmd.Parameters.Add("#Location", SqlDbType.VarChar).Value = location
con.Open()
cmd.ExecuteNonQuery()
End Using
Quickly translated from C#. I've tested it locally and it works. You should eventually wrap the code in a Using block to dispose and close the objects/connection properly.
Dim loc As String = "test"
Dim Command As New SqlCommand("spx_AddNewLoc")
Command.Parameters.Add("#Location", SqlDbType.VarChar).Value = loc
Dim Connection As New SqlConnection(connStr)
Command.Connection = Connection
Command.CommandType = CommandType.StoredProcedure
Connection.Open()
Command.ExecuteNonQuery()
Connection.Close()
C#
string storedProcedure = "spx_AddNewLoc";
string location = "Amsterdam";
using (SqlConnection connection = new SqlConnection(connStr))
using (SqlCommand command = new SqlCommand(storedProcedure, connection))
{
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add("#Location", SqlDbType.VarChar).Value = location;
connection.Open();
command.ExecuteNonQuery();
}
As far as you have changed it to a Stored Procedure, you should change .CommandType of your SqlCommand.
cmd.CommandType = CommandType.StoredProcedure;
SqlCommand.CommandType Property
Rename AddWithValue to Add. In your code AddWithValue accepts value as second param and I suspect it makes your parameter #Location of other type than varchar, that's why it cannot be found on a procedure execute. https://msdn.microsoft.com/en-us/library/wbys3e9s(v=vs.110).aspx

Text Box to retrieve information from database

I'm trying to display information on a piece of equipment the idea is that the user will type in an ID in the textbox and it will display the information on a grid view:
Dim ID As String = TxtSearch.Text
Dim cmd As SqlCommand
Dim ds As String = "Select * from Medical_Equipment where AssetID='" & ID & "''"
Dim strConnString As String = ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString
Dim con As New SqlConnection(strConnString)
cmd = New SqlCommand(ds, con)
Try
con.Open()
GridView1.EmptyDataText = "No equipment with that Asset ID"
GridView1.DataSource = cmd.ExecuteReader()
GridView1.DataBind()
Catch ex As Exception
Throw ex
Finally
con.Close()
con.Dispose()
End Try
End Sub
But it is not displaying the information Unclosed quotation mark after the character string '1001''.Incorrect syntax near '1001''
If AssetID is defined as numeric at database level the SQL statement should be:
"SELECT * FROM Medical_Equipment WHERE AssetID=" & ID
If it is defined as text then should be:
"SELECT * FROM Medical_Equipment WHERE AssetID='" & ID & "'"
I think you have a typo here:
Try this:
"Select * from Medical_Equipment where AssetID='" & ID & "'"

Display logged in user asp.net

I have made a little custom log-in page in asp.net, see code:
Dim strCon As String = ConfigurationManager.ConnectionStrings("Goed").ConnectionString
'Create Connection String And SQL Statement
Dim strSelect As String = "SELECT COUNT(*) FROM tbl_LogIn WHERE Gebruiker = #Gebruiker AND Wachtwoord = #Wachtwoord"
Dim con As New SqlConnection(strCon)
Dim cmd As New SqlCommand()
cmd.Connection = con
cmd.CommandType = CommandType.Text
cmd.CommandText = strSelect
Dim Gebruiker As New SqlParameter("#Gebruiker", _
SqlDbType.VarChar)
Gebruiker.Value = TxtUs.Text.Trim().ToString()
cmd.Parameters.Add(Gebruiker)
Dim Wachtwoord As New SqlParameter("#Wachtwoord", _
SqlDbType.VarChar)
Wachtwoord.Value = TxtPw.Text.Trim().ToString()
cmd.Parameters.Add(Wachtwoord)
con.Open()
Dim result As Integer = DirectCast(cmd.ExecuteScalar(), Int32)
con.Close()
If result >= 1 Then
Response.Redirect("default.aspx")
Else
lblMsg.Text = "Gebruikers naam en of wachtwoord kloppen niet"
End If
End Sub
As you can see it directs to Default.aspx.
On my defaults.aspx page I have a header. In this header I want a small label to sdhow the logged in user something like: Hello [User] How can this be done?
Using Sessions:
While Directing to new page (at Login.aspx-in button's onClick event)
Session["valueName"]=value;
On new page( default.aspx in your case) use:
Label1.Text=Session["valueName"].ToString();
Or you can use cookies as well:
CREATE:
Response.Cookies("userInfo")("userName") = "DiederikEEn"
Response.Cookies("userInfo")("lastVisit") = DateTime.Now.ToString()
Response.Cookies("userInfo").Expires = DateTime.Now.AddDays(1)
READING:
If Not Request.Cookies("userName") Is Nothing Then
Label1.Text = Server.HtmlEncode(Request.Cookies("userName").Value)
End If
If Not Request.Cookies("userName") Is Nothing Then
Dim aCookie As HttpCookie = Request.Cookies("userName")
Label1.Text = Server.HtmlEncode(aCookie.Value)
End If
More here:
Cookies
Sessions
If you can create header in your master page then you can add Hello [User] there and call the session.

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