Private Sub btnUpdate_Click(sender As Object, e As EventArgs) Handles btnUpdate.Click
Try
Dim con As New SqlConnection
Dim cmd As New SqlCommand
con.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=E:\Comp-296\Project1\Project1\Game_time.mdb"
con.Open()
cmd.Connection = con
cmd.Connection = con
cmd.CommandText = ("UPDATE User_Name SET User_Name = #User_Name, Game_Name = #Game_Name, Score = #Score, Time/Date = #Time/Date")
cmd.Parameters.Add("#User_Name", SqlDbType.VarChar).Value = txtUser.Text
cmd.Parameters.Add("#Game_Name", SqlDbType.VarChar).Value = txtGame.Text
cmd.Parameters.Add("#Score", SqlDbType.VarChar).Value = txtScore.Text
cmd.Parameters.Add("#Time/Date", SqlDbType.DateTime).Value = txtDate.Text
cmd.ExecuteNonQuery()
MessageBox.Show("Data Update successfully")
con.Close()
Catch ex As System.Exception
MessageBox.Show("Data Update has failed")
End Try
End Sub
The code is giving an Exception is an ArgumentException and also :Keyword not supported: 'provider'.
You are using Access. This database cannot be opened using the classes in System.Data.SqlClient. These classes are used when you want to connect to Sql Server, Sql Server Express or LocalDB.
If you want to reach an MSAccess database you need the classes in System.Data.OleDb and these classes are OleDbConnection, OleDbCommand etc...
Said that, please note, that your field Date/Time will give you headaches. Change that name or put always square brackets around it because the / will be interpreted as the division operator
So your code could be:
Using con = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=E:\Comp-296\Project1\Project1\Game_time.mdb")
Using cmd = new OleDbCommand("UPDATE User_Name
SET User_Name = #User_Name,
Game_Name = #Game_Name,
Score = #Score, [Time/Date] = #dt", con)
con.Open()
cmd.Parameters.Add("#User_Name", OleDbType.VarWChar).Value = txtUser.Text
cmd.Parameters.Add("#Game_Name", OleDbType.VarWChar).Value = txtGame.Text
cmd.Parameters.Add("#Score", OleDbType.VarWChar).Value = txtScore.Text
cmd.Parameters.Add("#dt", OleDbType.Date).Value = Convert.ToDateTime(txtDate.Text)
cmd.ExecuteNonQuery()
MessageBox.Show("Data Update successfully")
End Using
End Using
Other notes:
Disposable objects like the connection and the command should be enclosed inside a Using Statement to be disposed and closed as soon as possible.
The time field requires a DateTime value not a string. If you pass a string you will face the automatic conversion made by the engine and sometime the engine is unable to produce a valid date from your input string. This will raise another exception (DataType mismatch). Better check and convert the value before passing it.
Also the type of the parameters should be from the OleDbType enum.
Related
i am begginer in visual basic and i want to insert text into cells in column in MS access but i doesn't find, how could i do that.
Here is code i tried:
Private Sub UpdateDataBase2()
provider = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source="
datafile = "F:\Test Database\Database.accdb"
conString = provider & datafile
myConnection.ConnectionString = conString
myConnection.Open()
Dim str As String
str = "Insert into TABLA([LABELS]) Values (?)"
Dim cmd As OleDbCommand = New OleDbCommand(str, myConnection)
cmd.Parameters.Add(New OleDbParameter("LABELS", CType(TextBox1.Text, String)))
Select Case panelCount
Case 1
' TextBox1.Text = cmd.Add("LABELS").Rows(0).Item(1).ToString()
Case 2
' str = "Insert into TABLA([LABELS]) Values (?)"
'cmd.Parameters.Add(New OleDbParameter("LABELS", CType(TextBox1.Text, String)))
End Select
Try
cmd.ExecuteNonQuery()
cmd.Dispose()
myConnection.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
myConnection.Close()
End Sub
In this application, i made a dynamics panels and labels.(dynamics is for me generated in code)
panelcount is variable which saves to another MS acces database count of dynamics panels. I want to save text from labels to database systematically(it means: text from label 1 insert to cell 1.), but every code i tried was not function for me.
I know i have to use loop, but first i want to try if code works.
Sorry for my english.
Any solution?
Database objects like Connection and Command should be declared in the method where they are used so they can be disposed.
Use Using...End Using blocks to ensure that your database objects are closed and disposed even if there is an error.
Insert creates a new record. If you want to Update an existing record you will need the primary key value for the record you want to update.
Dim Str = Update TABLA Set [LABELS] = ? Where ID = ?
Then you will need a second parameter.
cmd.Parameters.Add("ID", OleDbType.Integer).Value = intID
You will need to declare and provide a value for intID.
Don't show a message box while a connection is open.
Private Sub OPCode()
Try
Dim Str = "Insert into TABLA([LABELS]) Values (?)"
Dim ConStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=F:\Test Database\Database.accdb"
Using myConnection As New OleDbConnection(ConStr),
cmd As OleDbCommand = New OleDbCommand(Str, myConnection)
cmd.Parameters.Add("LABELS", OleDbType.VarChar).Value = TextBox1.Text
myConnection.Open()
cmd.ExecuteNonQuery()
End Using 'Closes and disposes the connection and disposes the command
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
My question is "The user should be able to update (edit) a previously entered log but the date and the week number should be prevented from being edited"
How do I restrict user to not update the date and the week textbox?
Here is my current update code:
Private Sub Btnupdatelog_Click(sender As Object, e As EventArgs) Handles Btnupdatelog.Click
Dim conn As New SqlConnection
Dim cmd As New SqlCommand
cmd = New SqlCommand("update Logbook Objectives='" & Txtobjectives.Text & "',Contents='" & Txtcontent.Text & "',Company_Signature_Stamp='" & Txtsignature.Text & "',Company_Date='" & DateTimePicker2.Text & "' where LogId=" & TxtLogId.Text & "", conn)
conn.ConnectionString = "Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\Alex\source\repos\CurriculumVitae(CV)\bin\Debug\CurriculumVitae(CV).mdf;Integrated Security=True;Connect Timeout=30"
conn.Open()
cmd.ExecuteNonQuery()
conn.Close()
MsgBox("Update Successfully")
End Sub
End Class
To prevent certain fields from being update, simply don't include those fields in the command text. I removed the date field from the text.
Database objects need to be closed and disposed. Using...End Using blocks handle this for you even if there is an error. In this code, both the connection and command are included in the Using block. Note the comma at the end of the first line of the Using.
Never concatenate strings to build sql text. Always use parameters to avoid sql injection. I had to guess at the datatype and size of your fields. Check your database for the correct values.
Private Sub Btnupdatelog_Click(sender As Object, e As EventArgs) Handles Btnupdatelog.Click
Using conn As New SqlConnection("Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\Alex\source\repos\CurriculumVitae(CV)\bin\Debug\CurriculumVitae(CV).mdf;Integrated Security=True;Connect Timeout=30"),
cmd As New SqlCommand("update Logbook Set Objectives= #Objectives, Contents= #Contents, Company_Signature_Stamp= #Signature where LogId= #ID;", conn)
With cmd.Parameters
.Add("#Objectives", SqlDbType.VarChar, 300).Value = Txtobjectives.Text
.Add("#Contents", SqlDbType.VarChar, 300).Value = Txtcontent.Text
.Add("#Signature", SqlDbType.VarChar, 100).Value = Txtsignature.Text
.Add("#ID", SqlDbType.Int).Value = CInt(TxtLogId.Text)
End With
conn.Open()
cmd.ExecuteNonQuery()
End Using
MsgBox("Update Successfully")
End Sub
I have a simple blackjack game that I am trying to get to update a database by adding 2 simple values to it. I want it to add the username and the players' score to the database.
After watching an online tutorial this is the code I tried:
Imports System.Data.OleDb
Public Class Form1
'for updating database
Dim provider As String
Dim dataFile As String
Dim connString As String
Dim myConnection As OleDbConnection = New OleDbConnection
Private Sub ButtonSaveScore_Click(sender As Object, e As EventArgs) Handles ButtonSaveScore.Click
provider = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source="
dataFile = "F:\Documents\Class Documents\CSC289 - K6A - Programming Capstone Project\Project\BlackJack\BlackJack\Scoreboard.accdb"
connString = provider & dataFile
myConnection.ConnectionString = connString
myConnection.Open()
Dim str As String
str = "Update [Scores] set [UserName] = '" & playerName & "',[Score] =' " & wins & "' where [ID] = NEW"
Dim cmd As OleDbCommand = New OleDbCommand(str, myConnection)
Try
cmd.ExecuteNonQuery()
cmd.Dispose()
myConnection.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
I get the error:
one or more variables is not provided
The first time I hit the save button. The second time it breaks the application and it says that I "cannot adjust the files current state it is already open. It then highlights myConnection.ConnectionString = connString.
Consider implementing Using:
Sometimes your code requires an unmanaged resource, such as a file handle, a COM wrapper, or a SQL connection. A Using block guarantees the disposal of one or more such resources when your code is finished with them. This makes them available for other code to use.
Here is some sample code:
Using con As New OleDbConnection(connectionString),
cmd As New OleDbCommand(commandString, con)
con.Open()
cmd.ExecuteNonQuery()
End Using
This will handle the closing and disposing of your objects.
I would also consider using parameters to avoid SQL injection. See Bobby Tables for more information on this.
Here is some sample code:
Using con As New OleDbConnection(connectionString),
cmd As New OleDbCommand("UPDATE [Scores] SET [UserName] = ?, [Score] = ? WHERE [ID] = ?", con)
con.Open()
cmd.Parameters.Add("#Username", OleDbType.[Type]).Value = playerName
cmd.Parameters.Add("#Score", OleDbType.[Type]).Value = wins
'I've popped this into a parameter as I'm unsure what it is. I'll leave that for you to decide
cmd.Parameters.Add("#ID", OleDbType.[Type]).Value = "NEW"
cmd.ExecuteNonQuery()
End Using
Note that I have used OleDbType.[Type]. You will want to replace this with the data type you have specified for your columns.
With OleDb the order of your parameters is important, not the naming. Ensure that you create the parameters as they appear in your command as shown above.
I created a search button to query my MS Access database and display the results but whenever I type in the ID and click search button it does nothing.
Everything else is working, it copies data from the VB form and stores it in the MS Access database but the search button does not query the database and retrieve the data.
Below is my code for the search button:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSearch.Click
Dim found As Boolean
Try
cm = New OleDb.OleDbCommand
With cm
.Connection = cn
.CommandType = CommandType.Text
.CommandText = "SELECT* FROM tblInfo WHERE (ID = #ID & txtFind.Text = #ID)"
dr = .ExecuteReader
End With
While dr.Read()
found = True
txtFirst1.Text = dr("Pfirst").ToString
txtMid1.Text = dr("Pmiddle").ToString
txtLast1.Text = dr("Plast").ToString
txtAdd1.Text = dr("Paddress").ToString
txtPhone1.Text = dr("Pphone").ToString
txtContact1.Text = dr("Pcontact").ToString
End While
cn.Close()
Exit Sub
If found = False Then MsgBox("Patient ID not found!", MsgBoxStyle.Critical)
dr.Close()
Catch ex As Exception
End Try
How can I solve this?
The issue is the attempt to pass the value of txtFind.Text into the command.
You want to use parameters:
With cm
.Connection = cn
.CommandType = CommandType.Text
.CommandText = "SELECT * FROM tblInfo WHERE ID = ?"
.Parameters.Add("#ID", OleDbType.[Type]).Value = txtFind.Text
dr = .ExecuteReader
End With
Note that I have used OleDbType.[Type]. You will want to replace this with the data type you have specified for column ID.
It also looks like you have missed opening the connection before calling ExecuteReader():
cn.Open()
I would consider implementing Using:
Sometimes your code requires an unmanaged resource, such as a file handle, a COM wrapper, or a SQL connection. A Using block guarantees the disposal of one or more such resources when your code is finished with them. This makes them available for other code to use.
Here is some sample code:
Using con As New OleDbConnection(connectionString),
cmd As New OleDbCommand("SELECT * FROM tblInfo WHERE ID = ?", con)
con.Open()
cmd.Parameters.Add("#ID", OleDbType.[Type]).Value = txtFind.Text
dr = cmd.ExecuteReader()
...
End Using
just want to ask if what is the proper way on updating data in ms access Database, because when I use this code, my data is not updated and it doesn't show any error, so the returned value of the function is FALSE.
below is my code.
dim conn as new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\myDb.accdb;Persist Security Info=False;")
Protected Function UpdateProduct(ByVal productDetails As ProductModel) As Boolean
reopenConnection()
cmd = New OleDbCommand("UPDATE Product Set ProductName=#prodName, Price=#price, ProductDescription=#prodDesc, CategoryId=#catId where ProductId=#prodId;", conn)
cmd.CommandType = CommandType.Text
cmd.Parameters.Add("#prodId", OleDbType.VarChar).Value = productDetails.NewProductId
cmd.Parameters.Add("#prodName", OleDbType.VarChar).Value = productDetails.ProductName
cmd.Parameters.Add("#price", OleDbType.Decimal).Value = productDetails.Price
cmd.Parameters.Add("#prodDesc", OleDbType.VarChar).Value = productDetails.ProductDescription
cmd.Parameters.Add("#categoryId", OleDbType.Integer).Value = productDetails.CategoryId
Return cmd.ExecuteNonQuery() > 0
End Function
Private Sub reopenConnection()
If conn.State = ConnectionState.Open Then
conn.Close()
End If
conn.Open()
End Sub
Thanks
My experience with access is you have to commit the transactions or you never see the update in the database. See this stackoverflow thread for the syntax.
How to implement transaction way in vb.net?