double insertion into sql db by asp coding - asp.net

this code works fine but its inserts the same data twice in sql db on just one button click . if i made some mistake plz let me know ..
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim cmd As New SqlCommand
Dim str As String
str = "insert into cmember(name,period,design,duty,quali,cont)values ('" & TextBox1.Text & "', '" & TextBox2.Text & "','" & TextBox3.Text & "','" & TextBox4.Text & "', '" & TextBox5.Text & "','" & TextBox6.Text & "')"
If con.State = ConnectionState.Closed Then
con.Open()
End If
Try
cmd.CommandType = CommandType.Text
cmd.Connection = con
cmd.CommandText = str
Catch ex As Exception
MsgBox(e.ToString)
End Try
If cmd.ExecuteNonQuery Then
Label1.Text = "entry saved"
con.Close()
Else
Label1.Text = "entry not saved"
End If
End Sub

I can't see the valid reason why it inserts twice a same record in current code snippet. May be a button is hit twice or you are refreshing a web page.
Off-the topic : Do not use hard coded SQL statement. Use parameterized query. (Read about SQL Injection)
str = "insert into cmember (name,period,design,duty,quali,cont) values
(#name,#period,#design,#duty,#quali,#cont)"

This might seem silly, but you're not double clicking the button, are you ?
Also, never use a Msgbox call in ASP - the messagebox will appear on the server, not on the browser, and it will block the thread until clicked. You're much better to create an ASP Label control and assign the text to that.
Also, the bit enclosed in a Try block is just settings and will never throw an error - the try block should be around the commands where you open the connection, and where you execute the query.

Your code is not appearing to insert this data in twice.
The best way to find out what exactly is happening is to run a trace through SQL Server Profiler. To do this you need to ensure you have ALTER TRACE permissions on the instance.

Related

Insert data into .accdb (ms access) failed

I'm doing insert username and password into database in vb.net but it gives this error:
the error image
can someone take a look what cause it?
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
pro = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Amin\source\repos\Nando's\Nando's\user.accdb"
connstring = pro
myconnection.ConnectionString = connstring
myconnection.Open()
command = "insert into user ([USERNAME],[PASSWORD]) values ('" & USERNAMETextBox.Text & "','" & PASSWORDTextBox.Text & "')"
Dim cmd As OleDbCommand = New OleDbCommand(command, myconnection)
cmd.ExecuteNonQuery()
cmd.Dispose()
myconnection.Close()
MsgBox("Record added", MsgBoxStyle.Information)
End Sub
I change from this:
command = "insert into user ([USERNAME],[PASSWORD]) values ('" & USERNAMETextBox.Text & "','" & PASSWORDTextBox.Text & "')"
to this:
command = "insert into [user] ([USERNAME],[PASSWORD]) values ('" & USERNAMETextBox.Text & "','" & PASSWORDTextBox.Text & "')"
I just put a bracket at user and it is solved.
The bad thing is I was going back and forth between tutorial for days but neither of them solve it because the error was on the table name but it is finally solved. Thank you to Hursey for mentioning reserved words.

Login page not working in vb asp.net

I am having an issue with my login page. I am not getting any errors so am not able to know where the problem is?
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Login.Click
'connection string
Dim mysqlconn As MySqlConnection = New MySqlConnection("server=localhost;user id=root;Password=123;database=users;persist security info=False")
Dim cmd As New MySqlCommand
Dim da As New MySqlDataAdapter
Dim mydata As New DataTable
Dim reader As MySqlDataReader
Try
mysqlconn.Open()
Dim query As String
query = "SELECT * FROM login_form where Username = '" & rfvUser.Text & "' and Password='" & rfvPWD.Text & "'"
cmd = New MySqlCommand(query, mysqlconn)
reader = cmd.ExecuteReader
While reader.Read()
If rfvUser.Text = "admin" And rfvPWD.Text = "admin" Then
Me.Session("User") = Me.rfvUser.Text
Server.Transfer("Admin.aspx")
ElseIf (rfvUser.Text = reader("UserName").ToString()) And (rfvPWD.Text = reader("Password").ToString()) Then
Me.Session("User") = Me.rfvUser.Text
Server.Transfer("Ersal_send.aspx")
Else
ClientScript.RegisterStartupScript(Page.[GetType](), "validation", "<script language='javascript'>alert('Invalid Username or Password')</script>")
reader.Close()
End If
End While
Catch ex As Exception
MsgBox(ex.Message)
Finally
mysqlconn.Dispose()
End Try
End Sub
End Class
Have you tried running the query directly via a SQL client? If your query is not returning any rows, then your procedure will simply exit without any errors as it will never enter the While loop.
Another advice: It is never a good idea to pass user input directly into a query. This leads to SQL injection. Use parameterised queries. Google for it.

insert command inserts several rows in table

I'm using this code to insert in database , but every time it inserts more than one row ,what is the problem ?
Protected Sub btnSave_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSave.Click
Dim dob As DateTime = DateTime.Parse(Request.Form(TextBox6.UniqueID))
Dim conString As String = ConfigurationManager.ConnectionStrings("sqlexpress").ConnectionString
Using con As New System.Data.SqlClient.SqlConnection(conString)
Dim com As New SqlCommand("INSERT INTO main (GroupID, Name, Description, ModeUD, StartNum, StartDate, Rate) VALUES (" & TextBox1.Text & ",'" & TextBox2.Text & "','" & TextBox3.Text & "'," & Me.DropDownList1.SelectedItem.Value & "," & TextBox4.Text & ",'" & dob & "'," & TextBox5.Text & ")", con)
con.Open()
com.ExecuteNonQuery()
con.Close()
End Using
End Sub
Have you checked to see if your block of code is being called more than once? One quick way is to put a alert box inside so you can count the times it runs.
Well... there are lots of problems. The first of which is the potential for SQL Injection, you should be using named parameters. Another is that the line about Dim com As New... should also be in a Using clause.
However, nothing in that bit of code suggests that it is inserting more than 1 record. I suggest you put a break point on the ExecuteNonQuery line and see what's going on.
I have checked and hole the button click was executed twice , I have changed the code to this one and it has been solved , but I dont know why the click event is executed twice :
Dim i As Boolean = True
Protected Sub btnSave_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSave.Click
Dim dob As DateTime = DateTime.Parse(Request.Form(TextBox6.UniqueID))
Dim conString As String = ConfigurationManager.ConnectionStrings("sqlexpress").ConnectionString
Using con As New System.Data.SqlClient.SqlConnection(conString)
con.Open()
Using com As New SqlCommand("INSERT INTO main (GroupID, Name, Description, ModeUD, StartNum, StartDate, Rate) VALUES (" & TextBox1.Text & ",'" & TextBox2.Text & "','" & TextBox3.Text & "'," & Me.DropDownList1.SelectedItem.Value & "," & TextBox4.Text & ",'" & dob & "'," & TextBox5.Text & ")", con)
If i = True Then
com.ExecuteScalar()
i = False
End If
End Using
con.Close()
End Using
End Sub

What's wrong with this SELECt Query?

Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim SQLData As New System.Data.SqlClient.SqlConnection("Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True")
Dim cmdSelect As New System.Data.SqlClient.SqlCommand("SELECT COUNT(*) FROM Table1 WHERE Name =" + TextBox1.Text + " And Last = '" + TextBox2.Text + "'", SQLData)
SQLData.Open()
If cmdSelect.ExecuteScalar > 0 Then
Label1.Text = "Record Found ! " & TextBox1.Text & " " & TextBox2.Text
Return
End If
Label1.Text = "Record Not Found ! "
SQLData.Close()
End Sub
I write this code to find whether the record entered in textbox1 and textbox2 exists or not ..if record exist ..then in label1 the text would be RECORD FOUND else NO RECORD FOUND
ERROR :
**when i enter in textbox1 and textbox2 then on button click event it shows the error : Invalid column name ,,**
Please use SqlCommand.Parameters collection. Please!! For the sake of better programming.
Dim cmdSelect As New System.Data.SqlClient.SqlCommand(
"SELECT COUNT(*) FROM Table1 WHERE Name = #Name And Last = #Last", SQLData)
cmdSelect.Parameters.AddWithValue("#Name",TextBox1.Text)
cmdSelect.Parameters.AddWithValue("#Last",TextBox2.Text)
TextBox1.Text should be passed inside single quotes (').
Beside that, it seems to be another Little Bobby Tables case.
You need to add ' around the Textbox1.text value
e.g
'" + TextBox1.Text + "'
You should really not doing it like this since this is open for sql injection. Except from that I think you are missing some ' in the query around TextBox1.Text.

What is wrong with my this code, i think the select query is wrong?

What is wrong with my this code, i think the select query is wrong :
i have a textbox1, textbox2 and textbox3
when i type employee id in textbox1 and Email in textbox2 then in textbox3 the password will be retrieved according to employee id and email in database...
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
'Dim cmdSelect As New System.Data.SqlClient.SqlCommand("SELECT Password FROM a1_admins WHERE EmployeeId" = TextBox1.Text And "Email" = TextBox2.Text, SQLData)
Dim SQLData As New System.Data.SqlClient.SqlConnection("Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\ASPNETDB.MDF;Integrated Security=True;User Instance=True")
Dim cmdSelect As New System.Data.SqlClient.SqlCommand("SELECT Password FROM a1_admins WHERE EmployeeId =" & TextBox1.Text & "And" & "Email" = TextBox2.Text, SQLData)
SQLData.Open()
Dim dtrReader As System.Data.SqlClient.SqlDataReader = cmdSelect.ExecuteReader()
If dtrReader.HasRows Then
While dtrReader.Read()
TextBox3.Text = dtrReader("Password")
End While
Else
TextBox3.Text = ("No customer found for the supplied ID.")
End If
dtrReader.Close()
SQLData.Close()
End Sub
Why not giving your controls proper names?
Never ever build your query string by string concatination, use SqlParameter instead (Especially in a ASP.NET application!), to avoid sql injection.
Maybe you want to use HttpServerUtility.HtmlDecode too, to avoid injection of javascript and other nasty stuff on postback.
Use usings for disposable objects like SqlConnection and SqlDataReader
Yeah its definitely your SQL. There have to be syntax errors, because the query string is not concatenate correctly.
You haven't got quotes around the values, nor added any extra whitespace.
Really your query should have parameters in:
SELECT Password FROM a1_admins WHERE EmployeeId = #employeeID And Email = #email
It would have been useful if you had posted the actual error message.
However, I think your SQL query is missing some spaces. It should be:
Dim cmdSelect As New System.Data.SqlClient.SqlCommand("SELECT Password FROM a1_admins WHERE EmployeeId = " & TextBox1.Text & " And " & "Email = '" & TextBox2.Text & "'", SQLData)
Edit
As pointed out in other answers you should really be using parameters. I have provided a link to the MSDN article on using Parameters with the SQLCommand class
Try this (note the quotes) - assuming that EmloyeeId is an int and Email is some kind of varchar
Dim cmdSelect As New System.Data.SqlClient.SqlCommand("SELECT Password FROM a1_admins WHERE EmployeeId =" & TextBox1.Text & " And Email = '" & TextBox2.Text & "'", SQLData)

Resources