i have problem trying to delete record from my VS 2012 and i'm using sql server 2012, this is my task from my lecturer, and i cant solved it
now this is what i have
Private Sub bt_hapus_Click(sender As Object, e As EventArgs) Handles bt_hapus.Click
Try
Dim sqlda As New SqlClient.SqlDataAdapter("Delete from tabelpasien where No_Rkm_Mds=" & Me.txt_rkm_mds.Text, Me.SqlConnection1)
sqlda.Fill(dspasien, "tabelpasien")
MsgBox("Data telah berhasil dihapus")
bersih()
pasif()
normal()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
any help would be greatly apreciated...
A delete command is executed using an SqlCommand and the ExecuteNonQuery method.
Your code should be
Try
Dim cmd = New SqlClient.SqlCommand("Delete from tabelpasien where No_Rkm_Mds=#rkm", Me.SqlConnection1)
cmd.Parameters.AddWithValue("#rkm", Me.txt_rkm_mds.Text)
cmd.ExecuteNonQuery()
....
Using a parameterized query you don't have to put quotes around your where values (if the underlying field is any kind of char/varchar/nvarchar type) but, the most important benefit of a parameterized query is the elimination of a possible Sql Injection attack
You have forgotten your single quote marks I.E." ' " from around your condition.
Your statement Should be
Delete From tabelpasien where No_Rkm_Mds='" + Me.txt_rkm_mds.Text + "'"
If this is SQL SERVER, there shouldn't be a FROM in the statement.
Dim sqlda As New SqlClient.SqlDataAdapter("DELETE tabelpasien where No_Rkm_Mds=" & Me.txt_rkm_mds.Text, Me.SqlConnection1)
If No_Rkm_Mds is a VARCHAR or NVARCHAR, etc..., the value must be wrapped in 's.
Dim sqlda As New SqlClient.SqlDataAdapter("DELETE tabelpasien where No_Rkm_Mds=`" & Me.txt_rkm_mds.Text & "`", Me.SqlConnection1)
Finally, you should consider using SQL Parameters to avoid SQL injection.
Related
Currently cant get this to work, despite it being almost for verbatim the same as else where in my code.
Using con As New OleDbConnection(constring)
Using cmd As New OleDbCommand("UPDATE " & "`" & "SIQPERSIST" & "`" & " SET [Date_Added] = #Date_Added WHERE [BatchName] = #BatchName", con)
cmd.Parameters.AddWithValue("#BatchName", BatchName2)
cmd.Parameters.AddWithValue("#Date_Added", Date.Now.ToShortDateString)
con.Open()
cmd.ExecuteNonQuery()
con.Close()
End Using
End Using
I'm working in Vb.net
and i need to update all rows that have the name BatchName2 (this comes from a textbox)
with the current date.
The table they are on is SIQPERSIST.
The error i get is that its missing a parameter.
But i have don't know what parameter it needs despite almost similar code working else where, except the working code uses a WHERE KEY= 'keynumber' statement.
The issue is this uses backticks for the concatenated variable. Remember, ` and ' are not the same thing, and only one of those would work here.
It should look like something more like this:
Using con As New OleDbConnection(constring)
Using cmd As New OleDbCommand("UPDATE SIQPERSIST SET [Date_Added] = Date() WHERE [BatchName] = #BatchName", con)
cmd.Parameters.AddWithValue("#BatchName", BatchName2)
con.Open()
cmd.ExecuteNonQuery()
End Using
End Using
Note, there's no need to call con.Close() when you have a Using block to take care of that for you.
Additionally, not only did I convert BatchName2 to a real query parameter (Shame on you for adding concatenation to a query that already demonstrates how to use parameters!), but I was also able to convert the existing parameter to use get the date in the DB itself.
I'm trying to delete a record in my database via the ID, but it says
"Data Type mismatch in criteria expression."
Why do you think so?
Private Sub testdelete()
'THIS SAVES TO THE DEBUG ACCESS DATABASE!!!!!
Dim conn As New OleDbConnection
conn = New OleDbConnection
dbprovider = "Provider=Microsoft.ACE.OLEDB.12.0;"
Dim databasePath = "Data Source = FULL YUGIOH ACCESS DATABASE.accdb;"
conn.ConnectionString = dbprovider & databasePath
Dim Stringc As String = "delete from cmon11 where ID='" & TextBox2.Text & "'"
Dim command As OleDbCommand = New OleDbCommand(Stringc, conn)
Try
conn.Open()
command.ExecuteNonQuery()
command.Dispose()
conn.Close()
Catch ex As Exception
MsgBox(ex.Message)
Finally
conn.Dispose()
End Try
End Sub
As noted in the comments, a data type mismatch occurs because the where clause in your SQL statement is attempting to compare the value of your field ID (which you have stated is an integer) with a string value.
Following the concatenation, the SQL code might look something like this:
delete from cmon11 where ID='123'
Here, '123' is a string, not an integer - to supply an integer value, you would remove the single quotes to yield:
delete from cmon11 where ID=123
However, this does not solve the underlying issue of the potential for SQL injection when constructing SQL statements using values held by textboxes permitting arbitrary text input.
After modifying your code to remove the single quotes, consider the implications of your user typing the following into the textbox:
;drop table cmon11;--
The solution is to use parameters such that the query will fail in such circumstances, rather than performing unwanted actions. This answer from Erik is an excellent reference detailing the various ways to parameterise queries in MS Access.
The Using...End Using ensure that your database objects are closed and disposed even if there is an error.
Always use parameters to minimize type mismatches and protect against Sql Injection. I guessed at Integer for the datatype of the Id field but you will have to check your database for the actual datatype.
Private Sub testdelete()
Using conn As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source = FULL YUGIOH ACCESS DATABASE.accdb;")
Using command As New OleDbCommand("Delete From cmon11 Where ID= #ID;", conn)
command.Parameters.Add("#ID", OleDbType.Integer).Value = CInt(TextBox2.Text)
conn.Open()
command.ExecuteNonQuery()
End Using
End Using
End Sub
I am writing code to insert a username and password into a database called Users.
When I try to run the code it says there is an error in the INSERT statement's syntax but I cannot for the life of me find it.
I am running the SQL statement using another function called RunSQL that I can submit if need be but its worked fine with every other SQL statement I have run with it.
The Users table has the following columns with their data type
User_ID - Auto Number (Primary Key)
Username - Short Text
Password - Short Text
I have tried adding ' ' around the values I am going to insert into the table as well as removing the & and making it one continuous string. I have tried adding / removing the ; but nothing has worked.
Dim sql As String = "INSERT INTO Users (Username, Password) " &
"VALUES (" & username_Textbox.Text & " , " & password_Textbox.Text & ");"
RunSQL(sql)
MessageBox.Show("User Added")
Private Sub RunSQL(ByVal sql As String)
Dim conn As OleDbConnection = New
OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=Paper_Gen_Database.accdb;")
conn.Open()
Dim cmd As New OleDbCommand(sql, conn)
cmd.ExecuteNonQuery()
System.Threading.Thread.Sleep(500)
End Sub
The code should take the values from the username and password textboxes and insert them into the Users table but so far it has only thrown back an SQL error.
This is what the SQL statement looks when with "bh106" being the Username and "ZLTga" being the Password
This is one way to use parameters. It is very important to use parameters because otherwise you risk SQL injection which can ruin your database. It is actually much easier to write the SQL statement this way because you don't have to worry about if you have all your quotes in the string correctly.
The Using...End Using blocks ensure that your database objects are closed and disposed even if there is an error. This is important because it releases any unmanaged resources being used.
In a real application you would never save passwords as plain text but that is a subject for another day.
Private Sub InsertUser()
Dim sql As String = "INSERT INTO Users (Username, [Password]) VALUES (#username, #password);"
Using conn As OleDbConnection = New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=Paper_Gen_Database.accdb;")
Using cmd As New OleDbCommand(sql, conn)
cmd.Parameters.Add("#username", OleDbType.VarChar).Value = username_Textbox.Text
cmd.Parameters.Add("#password", OleDbType.VarChar).Value = password_Textbox.Text
conn.Open()
cmd.ExecuteNonQuery()
End Using
End Using
MessageBox.Show("User Added")
End Sub
In Access the order that the parameters are added must match the order that they appear in the SQL statement.
Try this (its probably because of lack of quotes, and also because password is protected word):
Dim sql As String = "INSERT INTO Users (Username, [Password]) " &
"VALUES ('" & username_Textbox.Text & "' , '" & password_Textbox.Text & "');"
RunSQL(sql)
MessageBox.Show("User Added")
Also be aware of sql injection problem.
If a user will put a quote inside a textbox, insert will still fail.
You should try converting your code into parametrized query, example:
https://learn.microsoft.com/pl-pl/dotnet/api/system.data.oledb.oledbcommand.parameters?view=netframework-4.7.2
I am new to this forum, please could you help me get this code to work, when i execute it, it simply does nothing and does not update the DB. If i remove the square brackets it gives an error: "SYNTAX ERROR in UPDATE statement"
Any help appreciated!
Dim connection As OleDbConnection
connection = New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=UserDB.accdb;Jet OLEDB:Database;")
connection.Open()
Dim pass As String
pass = txtconfirm.Text
Dim user As String
user = LoginForm.UsernameTextBox.Text
Dim query As String = "UPDATE [Users] SET [Password]= '" & pass & "' WHERE [Username]= '" & user & "';"
Dim command As New OleDbCommand(query, connection)
command.ExecuteNonQuery()
connection.Close()
Given your actual connection string, the database that will be updated is the one in the directory where your application starts. This means that if you work with a WinForms application this folder is \BIN\DEBUG or x86 variant. If there is not error then you could get the return value of the ExecuteNonQuery call to verify if a record has been updated or not
Dim rowsUpdated = command.ExecuteNonQuery()
MessageBox.Show("Record updated count = " & rowsUpdated)
If this value is not zero then your database has been updated and you are looking for changes in the wrong database. Check the one in the BIN\DEBUG folder.
In any case your code has big problems. If your variables user or pass contain a single quote, then your code will crash again because your string concatenation will form an invalid SQL. As usual the only workaround is to use a parameterized query
Dim pass = txtconfirm.Text
Dim user = LoginForm.UsernameTextBox.Text
Dim query As String = "UPDATE [Users] SET [Password]= #p1 WHERE [Username]= #p2"
Using connection = New OleDbConnection("...........")
Using command As New OleDbCommand(query, connection)
connection.Open()
command.Parameters.Add("#p1", OleDbType.VarWChar).Value = pass
command.Parameters.Add("#p2", OleDbType.VarWChar).Value = user
command.ExecuteNonQuery()
End Using
End Using
The parameterized approach has many advantages. Your query text is more readable, there is no misunderstanding between your code and the values expected by your database engine. And while not easy to exploit with MS-Access there is no problem with Sql Injection
I think Steve presents a much better approach for you coding this...
Let me just throw out a few more things:
The reason you can't take those brackets out is some of your column names are reserved words; just FYI.
Since you report "it does nothing..." when you execute, it sounds like you have a valid connection and sql syntax, in which case my next step would be to copy the sql command text while in debug mode, change it to a select and run it in your DB. You should get one result when you do. If not, either your criteria or field contents are not what you think they are...
Just change the Update table SET field-value ... to SELECT * FROM table and leave the WHERE clause as is.
having this code (which i know the open/executenonquery/close conection in for loop is absolutely horrible).
Public Shared Sub salvarDatos(ByRef conexion As SqlConnection, ByRef datos As List(Of DatoBdReloj))
For i = 0 To datos.Count - 1
Dim laQuery As String = "Insert INTO MARCADASRELOJ (COD_MAR_RELOJ,FECHA_RELOJ,HORA_RELOJ,MINUTOS_RELOJ,NRO_RELOJ,NRO_TARJ) " & _
"VALUES (#codMarReloj,#fechaReloj,#horaReloj,#minutosReloj,#nroReloj,#nroTarj)"
Dim datoReloj As DatoBdReloj = datos.Item(i)
Dim command As SqlCommand = New SqlCommand(laQuery, conexion)
command.Parameters.AddWithValue("codMarReloj", datoReloj.tipoMarca)
command.Parameters.AddWithValue("fechaReloj", datoReloj.fechaHoraMarcaDT)
command.Parameters.AddWithValue("horaReloj", datoReloj.fechaHoraMarcaDT.Hour)
command.Parameters.AddWithValue("minutosReloj", datoReloj.fechaHoraMarcaDT.Minute)
command.Parameters.AddWithValue("nroReloj", datoReloj.idReloj)
command.Parameters.AddWithValue("nroTarj", datoReloj.idUsuario)
conexion.Open()
command.ExecuteNonQuery()
conexion.Close()
Next
End Sub
I don't have much experience with .net , but for what i have read using the AddWithValue method i can prevent sql injections and according to the "book" is the right way to do it (tell me if i'm wrong).
using a sentence like "Insert into xxx (x1,x2,x3) values ("val","val","val"),(...),(...)" to insert multiple rows is not an option for me because my database is running with sql 2005.
How can i take away that horrible open/execute/close inside the for loop to insert multiple rows no matter if it's sql 2005 or 2008 and also keep being secure from sql injections by using the AddWithValue Method?
Thanks! :)
Hello you can use bulkinsert
The code: BulkInserter
How to use it