Here is the code I am using :
Try
Dim SqlQuery As String = "DELETE FROM tblEXcel WHERE ID = " & id & ";"
Dim SqlCommand As New OleDbCommand
With SqlCommand
.CommandText = SqlQuery
.Connection = conn
.ExecuteNonQuery()
End With
MsgBox("One record deleted..")
Catch ex As Exception
MsgBox(ex.Message, vbOKOnly, "Clear Measurement Table!")
End Try
For DataBindings you can use this...
Do While ExampleBindingSource.Count > 0
ExampleBindingSource.RemoveCurrent()
Loop
Remove WHERE ID = " & id. Then ALL the rows will be deleted.
So, simply change your SQL command to:
Dim SqlQuery As String = "DELETE FROM tblEXcel"
use below statement:
delete * from tblName
Dim SqlQuery As String = "DELETE * FROM tblEXcel WHERE ID = " & id & ";"
Dim MySQLCON As MySqlConnection = New MySqlConnection("Data Source=localhost;Database=test;User ID=root;Password=mysql;")
Dim COMMAND As MySqlCommand
MySQLCON.Open() /Open your Connection
Dim DELETERECORD As String = "DELETE * FROM tblEXcel WHERE ID= #id"
COMMAND = New MySqlCommand(DELETERECORD, MySQLCON)
COMMAND.Parameters.AddWithValue("#id", userID.Text) /userID.Text is the string of the users ID
COMMAND.ExecuteNonQuery()
MySQLCON.Close() /Always Close your Connection
MySQLCON.Dispose() /Always Dispose of your Connection
Note:
The way you where doing it was vulnerable to MySQL Injection Attacks. If you have a lot of MySQL Code in your application, i advise you to rewrite it in the way so it is not vulnerable.
Related
I have successfully managed to use SELECT and DELETE SQL statements and now I am trying to use INSERT INTO. However I keep getting this error:
ExecuteNonQuery requires an open and available Connection. The
connection's current state is closed.
So I tried putting con.Open() to see if that would help and I got this error:
The ConnectionString property has not been initialized.
I was wondering if anyone knows what I have done wrong. Or just if anyone has any working code. Preferably I would like to not use parameters if that is possible because I don't understand them at all. Here is my SQL code:
Dim con As OleDb.OleDbConnection
Dim comm As OleDb.OleDbCommand
con = SQLConnect()
comm = New OleDb.OleDbCommand()
comm.CommandText = "INSERT INTO " & TableName & " (" & Column & ") VALUES (" & Value & ")"
comm.Connection = con
comm.ExecuteNonQuery()
con.Close()
Here is the connection code:
Public Function SQLConnect() As OleDb.OleDbConnection
If Connector.State = ConnectionState.Open Then
dbprovider = "PROVIDER=Microsoft.ACE.OLEDB.12.0;"
dbsource = "Data Source = NEA.accdb"
Connector.ConnectionString = dbprovider & dbsource
Connector.Open()
End If
Return Connector
End Function
Use one open connection and one close connection like this:
Open the connection
Execute all your DELETE and INSERT queries.
Close the connection.
Try this:
con.Open()
comm.Connection = con
comm.CommandText = "DELETE ..."
comm.ExecuteNonQuery()
comm.CommandText = "INSERT INTO " & TableName & " (" & Column & ") VALUES (" & Value & ")"
comm.ExecuteNonQuery()
con.Close()
BTW, I recommend that you use parameters instead of string concatenation on your sql query. To avoid sql injection.
I can select the data from an Access database, but I tried many ways to INSERT INTO database. There is no error message, but it didn't insert the data.
Code:
Dim conn As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & CurDir() & "\fsDB1.accdb")
Dim cmd As OleDbCommand
Dim dr As OleDbDataReader
conn.Open()
Dim CommandString As String = "INSERT INTO tblfile(stdUname,filePw,filePath,status) VALUES('" & userName & "','" & filePw & "','" & filePath & "','A')"
Dim command As New OleDbCommand(CommandString, conn)
Command.Connection = conn
Command.ExecuteNonQuery()
I just want a simple easy way to INSERT INTO an Access database. Is it possible because of the problem of Access database? I can insert this query by running query directly in Access.
Firstly I would check the database settings. If your app copies a new copy of the database each time you run it that would explain why you can select existing data and why your new data is not being saved (Well it is being saved, but the database keeps getting replaced with the old one). Rather set it up to COPY IF NEWER.
Further, you should ALWAYS use parameterized queries to protect your data. It is also is less error prone than string concatenated commands ans is much easier to debug.
Also, I recommend using a USING block to handle database connections so that your code automatically disposes of resources no longer needed, just in case you forget to dispose of your connection when you are done. Here is an example:
Using con As New OleDbConnection
con.ConnectionString = "Provider = Microsoft.ACE.OLEDB.12.0; " & _
"Data Source = "
Dim sql_insert As String = "INSERT INTO Tbl (Code) " & _
"VALUES " & _
"(#code);"
Dim sql_insert_entry As New OleDbCommand
con.Open()
With sql_insert_entry
.Parameters.AddWithValue("#code", txtCode.Text)
.CommandText = sql_insert
.Connection = con
.ExecuteNonQuery()
End With
con.Close()
End Using
Here is an example where data operations are in a separate class from form code.
Calling from a form
Dim ops As New Operations1
Dim newIdentifier As Integer = 0
If ops.AddNewRow("O'brien and company", "Jim O'brien", newIdentifier) Then
MessageBox.Show($"New Id for Jim {newIdentifier}")
End If
Back-end class where the new primary key is set for the last argument to AddNewRow which can be used if AddNewRow returns true.
Public Class Operations1
Private Builder As New OleDbConnectionStringBuilder With
{
.Provider = "Microsoft.ACE.OLEDB.12.0",
.DataSource = IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Database1.accdb")
}
Public Function AddNewRow(
ByVal CompanyName As String,
ByVal ContactName As String,
ByRef Identfier As Integer) As Boolean
Dim Success As Boolean = True
Dim Affected As Integer = 0
Try
Using cn As New OleDbConnection With {.ConnectionString = Builder.ConnectionString}
Using cmd As New OleDbCommand With {.Connection = cn}
cmd.CommandText = "INSERT INTO Customer (CompanyName,ContactName) VALUES (#CompanyName, #ContactName)"
cmd.Parameters.AddWithValue("#CompanyName", CompanyName)
cmd.Parameters.AddWithValue("#ContactName", ContactName)
cn.Open()
Affected = cmd.ExecuteNonQuery()
If Affected = 1 Then
cmd.CommandText = "Select ##Identity"
Identfier = CInt(cmd.ExecuteScalar)
Success = True
End If
End Using
End Using
Catch ex As Exception
Success = False
End Try
Return Success
End Function
End Class
Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
Dim READER As MySqlDataReader
Dim Query As String
Dim connection As MySqlConnection
Dim COMMAND As MySqlCommand
Dim item As Object
Try
item = InputBox("What is the item?", "InputBox Test", "Type the item here.")
If item = "shoe" Then
Dim connStr As String = ""
Dim connection As New MySqlConnection(connStr)
connection.Open()
Query = "select * from table where username= '" & Login.txtusername.Text & " '"
COMMAND = New MySqlCommand(Query, connection)
READER = COMMAND.ExecuteReader
If (READER.Read() = True) Then
Query = "UPDATE table set noOfItems = noOfItems+1, week1 = 'found' where username= '" & Login.txtusername.Text & "'"
Dim noOfItems As Integer
Dim username As String
noOfItems = READER("noOfItems") + 1
username = READER("username")
MessageBox.Show(username & "- The number of items you now have is: " & noOfGeocaches)
End If
Else
MsgBox("Unlucky, Incorrect item. Please see hints. Your score still remains the same")
End If
Catch ex As Exception
MessageBox.Show("Error")
End Try
I finally got the message box to display! but now my code does not increment in the database, can anybody help me please :D
Thanks in advance
After fixing your typos (space after the login textbox and name of the field retrieved) you are still missing to execute the sql text that updates the database.
Your code could be simplified understanding that an UPDATE query has no effect if the WHERE condition doesn't find anything to update. Moreover keeping an MySqlDataReader open while you try to execute a MySqlCommand will trigger an error in MySql NET connector. (Not possible to use a connection in use by a datareader). We could try to execute both statements in a single call to ExecuteReader separating each command with a semicolon and, of course, using a parameter and not a string concatenation
' Prepare the string for both commands to execute
Query = "UPDATE table set noOfItems = noOfItems+1, " & _
"week1 = 'found' where username= #name; " & _
"SELECT noOfItems FROM table WHERE username = #name"
' You already know the username, don't you?
Dim username = Login.txtusername.Text
' Create the connection and the command inside a using block to
' facilitate closing and disposing of these objects.. exceptions included
Using connection = New MySqlConnection(connStr)
Using COMMAND = New MySqlCommand(Query, connection)
connection.Open()
' Set the parameter value required by both commands.
COMMAND.Parameters.Add("#name", MySqlDbType.VarChar).Value = username
' Again create the reader in a using block
Using READER = COMMAND.ExecuteReader
If READER.Read() Then
Dim noOfItems As Integer
noOfItems = READER("noOfItems")
MessageBox.Show(username & "- The number of items you now have is: " & noOfItems )
End If
End Using
End Using
End Using
i used this coding for my update button to update data in my table in datagridview but it is still shows error. i need some help to solve this problem
Dim MyItems As Integer
Dim MyItemNo As Integer
Dim ItemDescription As String
MyItems = GridViewItems.CurrentRow.Index
MyItemNo = GridViewItems.Item(0, MyItems).Value
ItemDescription = GridViewItems.Item(1, MyItems).Value
Dim SqlQuery As String = " UPDATE ITEMS = '" & MyItems & "'WHERE Item_No = " & MyItemNo & ""
Dim SqlCommand As OleDbCommand
With SqlCommand
.CommandText = SqlQuery
.Connection = conn
.ExecuteNonQuery()
End With
Your use of the UPDATE sql statement is wrong. The correct syntax is
UPDATE <tablename> SET <field1> = <value>, <field2> = <value> WHERE <field3> = <value>
but there is also the problem of string concatenation that should be addressed.
So you could rewrite your code as
Dim SqlQuery As String = "UPDATE yourTableName SET ITEMS = ? WHERE Item_No = ?"
Dim SqlCommand As OleDbCommand
With SqlCommand
.CommandText = SqlQuery
.Connection = conn
.Parameters.AddWithValue("#p1", MyItems)
.Parameters.AddWithValue("#p2", MyItemNo)
.ExecuteNonQuery()
End With
This is an example of a parameterized query. You should always use this approach when you need to pass values submitted by your user to your database. Without this your code is open to SQL Injection and other parsing problems
Does anyone knows how to fix this code to and make it work properly?. I want to update my DB that will get the value in Combo box. Is it possible to update 1 or more value at the same time in DB?
CODE
cmd.CommandText = "UPDATE tblStudent SET (course = '" & ComboBox2.Text & "',section = '" & ComboBox5.Text & "') WHERE yearLevel = '" & yearLevel.Text & "';"
Thanks in advance!!
First, you should use sql-parameters instead of string concatenation to prevent possible sql-injection.
Also, your code already updates multiple records if there are more than one with the same yearLevel.
Dim sql = "UPDATE tblStudent SET course = #course,section = #section WHERE yearLevel = #yearLevel"
Using cmd = New SqlCommand(sql, con)
Dim p1 As New SqlParameter("#course", SqlDbType.VarChar)
p1.Value = ComboBox2.Text
cmd.Parameters.Add(p1)
Dim p2 As New SqlParameter("#course", SqlDbType.VarChar)
p2.Value = ComboBox5.Text
cmd.Parameters.Add(p2)
Dim p3 As New SqlParameter("#course", SqlDbType.Int)
p3.Value = Int32.Parse(yearLevel.Text)
cmd.Parameters.Add(p3)
Dim updatedCount = cmd.ExecuteNonQuery()
End Using
Note that i didn't know the data -type of your columns, so modify it accordingly. I just wanted to show you that it's important to use the correct type in the first place.
This is is for 'INSERTING', however, it can be adapted for 'UPDATING' quite easily:
Dim con As New SqlConnection
Dim cmd As New SqlCommand
Try
con.ConnectionString = "Data Source=atisource;Initial Catalog=BillingSys;Persist Security Info=True;User ID=sa;Password=12345678"
con.Open()
cmd.Connection = con
cmd.CommandText = "INSERT INTO table([field1], [field2]) VALUES([Value1], [Value2])"
cmd.ExecuteNonQuery()
Catch ex As Exception
MessageBox.Show("Error while inserting record on table..." & ex.Message, "Insert Records")
Finally
con.Close()
End Try
source: can be found here
where you have declared field1, and assigned it Combobox2.SelectedValue etc