couldnt save current locked by another user - sql

When i trying to browse and choose some image into picture box and then i click update button
it's error message pop up and display couldnt be save current locked by another user.
If lblTable.Text = "Visitor_ApplyPass" Then
Dim fsr As New FileStream(OpenFileDialog1.FileName, FileMode.Open, FileAccess.Read)
Using br As New BinaryReader(fsr)
Dim imgbuffer(fsr.Length) As Byte
br.Read(imgbuffer, 0, fsr.Length)
fsr.Close()
Using con As New OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0; Data Source=..\VisitorPass.accdb")
con.Open()
Dim sql As String
sql = "Update " & lblTable.Text & " set Visitor_Name='" & txtName.Text & "',[Visitor_Photo]= #imgfile where [VisitorApply_ID]=" & lblID2.Text & ""
Using cmd As New OleDbCommand(sql, con)
cmd.Parameters.AddWithValue("#imgfile", imgbuffer)
cmd.ExecuteNonQuery()
MsgBox("profile is updated")
con.Close()
End Using
End Using
End Using
Me.Close()

Related

How to update access db by editing datagridview cells?

Im trying to edit items after inserting to access by clicking the save button? How can i save the edits done in datagridview rows to access?
Already tried the update query
For each loop
vb.net
Private Sub BunifuFlatButton1_Click(sender As Object, e As EventArgs) Handles BunifuFlatButton1.Click
Dim constring As String = ("Provider=Microsoft.ACE.OLEDB.12.0;Data Source= C:\Users\PU-IMO\Desktop\BlueWavesIS - Copy\BlueWavesIS\BlueWavesIS.accdb")
Dim conn As New OleDbConnection(constring)
For Each row As DataGridViewRow In DataGridView1.Rows
Using con As New OleDbConnection(constring)
'nettxt.Text = (grosstxt.Text * perdistxt.Text / 100) - (dislctxt.Text + disusd.Text + distax.Text)
Dim cmd As New OleDbCommand("Update PurchaseInvoice set [Itemnum] = #ItemNum, [Itemname]= #ItemName, [Itemqty]= #ItemQty, [Itemprice] = #ItemPrice, [discount] =#discount, [subtotal] = #subtotal,[Preference] = " & preftxt.Text & ", [Suppnum] = " & pnumtxt.Text & ", [UniqueID] = " & pautotxt.Text & " Where [UniqueID] = " & pautotxt.Text & "", con)
cmd.Parameters.AddWithValue("#ItemID", row.Cells("ItemID").Value)
cmd.Parameters.AddWithValue("#ItemName", row.Cells("ItemName").Value)
cmd.Parameters.AddWithValue("#ItemQty", row.Cells("ItemQty").Value)
cmd.Parameters.AddWithValue("#ItemPrice", row.Cells("ItemPrice").Value)
cmd.Parameters.AddWithValue("#discount", row.Cells("discount").Value)
cmd.Parameters.AddWithValue("#subtotal", row.Cells("subtotal").Value)
cmd.Parameters.AddWithValue("#Ref", preftxt.Text.ToString)
cmd.Parameters.AddWithValue("#Suppnum", Convert.ToInt32(pnumtxt.Text))
cmd.Parameters.AddWithValue("#UniqueID", Convert.ToInt32(pautotxt.Text))
DataGridView1.AllowUserToAddRows = False
con.Open()
cmd.ExecuteNonQuery()
con.Close()
End Using
Next
'This the code i used to show the data in datagridview:
Private Sub NewPurchaseInvoice_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim con As New OleDbConnection
con.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source= C:\Users\PU-IMO\Desktop\BlueWavesIS - Copy\BlueWavesIS\BlueWavesIS.accdb"
con.Open()
Dim sql As String = "Select [Itemnum],[Itemname],[Itemprice],[ItemQty],[discount],[subtotal] from PurchaseInvoice where [UniqueID] = " & pautotxt.Text & ""
Dim cmd10 As OleDbCommand = New OleDbCommand(Sql, con)
'Dim adap As New OleDbDataAdapter("Select [Itemnum],[Itemname],[Itemprice],[discount],[subtotal] from PurchaseInvoice where UniqueID = " & pautotxt.Text & "", con)
'Dim ds As New System.Data.DataSet
'adap.Fill(ds, "PurchaseInvoice")
Dim dr As OleDbDataReader = cmd10.ExecuteReader
Do While dr.Read()
DataGridView1.Rows.Add(dr("ItemNum"), dr("ItemName"), dr("ItemQty"), dr("ItemPrice"), dr("discount"), dr("subtotal"))
Loop
con.Close()
I expect that all the rows will be updated as each other, but the actual output is that each row has different qty name etc...
This code does not seem appropriate in the load event because pautotxt.Text will not have a value yet. Can you move it to a Button.Click?
I guessed that the datatype of ID is an Integer. You must first test if the the .Text property can be converted to an Integer. .TryParse does this. It returns a Boolean and fills IntID that was provided as the second parameter.
You can pass the connection string directly to the constructor of the connection. The Using...End Using blocks ensure that your database objects are closed and disposed even if there is an error. You can pass the Select statement and the connection directly to the constructor of the command.
ALWAYS use Parameters, never concatenate strings to avoid sql injection. Don't use .AddWithValue. See http://www.dbdelta.com/addwithvalue-is-evil/
and
https://blogs.msmvps.com/jcoehoorn/blog/2014/05/12/can-we-stop-using-addwithvalue-already/
and another one:
https://dba.stackexchange.com/questions/195937/addwithvalue-performance-and-plan-cache-implications
The DataAdapter will open the connection, fiil the DataTable and close the connection if it finds it closed; however if it is found open it will leave it open.
The last line binds the grid to the DataTable.
Private Sub FillGrid()
If Not Integer.TryParse(pautotxt.Text, IntID) Then
MessageBox.Show("Please enter a number")
Return
End If
dt = New DataTable()
Using con As New OleDbConnection(ConnString)
Using cmd As New OleDbCommand(Sql, con)
cmd.Parameters.Add("#ID", OleDbType.Integer).Value = IntID
Dim adap = New OleDbDataAdapter(cmd)
adap.Fill(dt)
End Using
End Using
DataGridView1.DataSource = dt
End Sub
DataTables are very clever. When bound to a DataGridView they keep track of changes and mark rows as update, insert, or delete. The DataAdapter uses this info to update the database. Once the database is updated we call .AcceptChanges on the DataTable to clear the marking on the rows.
Private Sub UpdateDatabase()
Using cn As New OleDbConnection(ConnString)
Using da As New OleDbDataAdapter(Sql, cn)
da.SelectCommand.Parameters.Add("#ID", OleDbType.Integer).Value = IntID
Using builder As New OleDbCommandBuilder(da)
da.Update(dt)
End Using
End Using
End Using
dt.AcceptChanges()
End Sub

sqlite update in a loop take to long

I am updating only 20 rows in a loop but the best performance I get is around 2.5 seconds for the 20 rows.
What can I do to make this simple update faster?
This is what Iv'e tried:
Dim connectionString As New SQLite.SQLiteConnection("data source=" & Application.StartupPath & "\db.db3; Version=3;")
Dim connection = New SQLite.SQLiteConnection(connectionString)
connection.Open()
Dim com3 As New System.Data.SQLite.SQLiteCommand(connection)
For Each row As DataRow In table.Rows
com3.CommandText = "UPDATE Results SET LastScore=" & row.Item("position") & " WHERE TeamID='" & row.Item("teamid") & "'"
com3.ExecuteNonQuery()
Next
connection.Close()
AND
Dim connectionString As New SQLite.SQLiteConnection("data source=" & Application.StartupPath & "\db.db3; Version=3;")
Using con As New SQLiteConnection(connectionString)
con.Open()
Using c As New SQLiteCommand(con)
c.CommandText = "UPDATE Results SET LastScore= #Pos WHERE TeamID = #ID"
For Each row As DataRow In table.Rows
c.Parameters.AddWithValue("#Pos", row.Item("position"))
c.Parameters.AddWithValue("#ID", row.Item("teamid"))
c.ExecuteNonQuery()
Next
End Using
con.Close()
End Using
Thanks to muffi's answer this is now resolved. Add BeginTransaction()
Dim connectionString As New SQLite.SQLiteConnection("data source=" & Application.StartupPath & "\db.db3; Version=3;")
Using con As New SQLiteConnection(connectionString)
con.Open()
Using t As SQLiteTransaction = con.BeginTransaction()
Using c As New SQLiteCommand(con)
c.CommandText = "UPDATE Results SET LastScore= #Pos WHERE TeamID = #ID"
For Each row As DataRow In table.Rows
c.Parameters.AddWithValue("#Pos", row.Item("position"))
c.Parameters.AddWithValue("#ID", row.Item("teamid"))
c.ExecuteNonQuery()
Next
End Using
t.Commit()
End Using
con.Close()
End Using

A Generic Error occurred in GDI+ Saving Picturebox into ole database

I'm trying to save a picturebox into an ole database.
Here's my code :
Dim stream As New IO.MemoryStream
PictureBox1.Image.Save(stream, Imaging.ImageFormat.Jpeg)
Try
Dim query As String = "INSERT INTO Guestinfo ([GuestName],[Phone],[Idofguest],[Room],[Arrival],[Checkout],[Address],[IDImage]) VALUES ('" & TextBox1.Text & "','" & TextBox2.Text & "','" & TextBox3.Text & "','" & TextBox5.Text & "','" & DateTimePicker1.Text & "','" & DateTimePicker2.Text & "','" & TextBox4.Text & "',(#IDImage))"
Dim command As New OleDbCommand
With command
.CommandText = query
.Parameters.AddWithValue("#Picture", stream.GetBuffer())
.Connection = conn
.ExecuteNonQuery()
End With
MsgBox("Saved Successfully!", MsgBoxStyle.Information)
conn.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
In "A Generic Error occurred in GDI+" this error appear:
PictureBox1.Image.Save(stream, Imaging.ImageFormat.Jpeg)
By the way, my column type is Ole Object.
I hope someone help me ...
This application has an Open Button which will help you open any picture file to a PictureBox on the form using OpenFileDialog. You will see the path of the picture file in a disabled TextBox. When you click the update button the Picture's path is saved to an Access Database.
Follow the steps below to create a similar project for yourself:
* Create a new Visual Basic.net project. Select Windows Forms Application from New Project Dialog Box. Name this application whatever you want.
* Create the following with below mentioned properties:
- Form - (Name): sample, Text: FormPictureApplication
- PictureBox - (Name): PictureBox1, SizeMode: StretchImage
- Button - (Name): ButtonUpdate, Text: &Update
- Button - (Name): ButtonOpen, Text: &Open
- TextBox - (Name): TextBoxPictureFilePath, Enabled: False
Double Click the Form, insert the following code right above Public Class {...}:
Imports System.Data.OleDb
Imports System.IO
Imports Microsoft.Win32
Double Click ButtonOpen and insert the following code:
Dim img As String
Dim myStream As Stream = Nothing
Dim openFileDialog1 As New OpenFileDialog()
openFileDialog1.InitialDirectory = "c:\"
openFileDialog1.Filter = Nothing
openFileDialog1.FilterIndex = 2
openFileDialog1.RestoreDirectory = True
openFileDialog1.FileName = ""
If openFileDialog1.ShowDialog() = System.Windows.Forms.DialogResult.OK Then
Try
myStream = openFileDialog1.OpenFile()
If (myStream IsNot Nothing) Then
TextBoxPictureFilePath.Text = ""
img = openFileDialog1.FileName
PictureBox1.Image = System.Drawing.Bitmap.FromFile(img)
TextBoxPictureFilePath.Text = openFileDialog1.FileName
End If
Catch Ex As Exception
MessageBox.Show("Cannot read file from disk. Original error: " & Ex.Message)
Finally
If (myStream IsNot Nothing) Then
myStream.Close()
End If
End Try
End If
Create a Microsoft Access Database in your convenient location and name it as Databasemikeoe2003PictureApplication.mdb
Create a table with the name Tablemikeoe2003PictureApplication and add following Columns to it:
Id - Datatype: Autonumber
PicturePath - DataType: Memo (as file paths can be considerably long at times)
Double Click the UpdateButton and insert the following code:
Try
Dim myConnection As OleDbConnection
Dim myCommand As OleDbCommand
Dim mySQLString As String
myConnection = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Databasemikeoe2003PictureApplication.mdb;")
myConnection.Open()
mySQLString = "INSERT INTO Tablemikeoe2003PictureApplication (PicturePath) VALUES('" & Replace$(TextBoxPictureFilePath.Text, "'", "''") & "')"
myCommand = New OleDbCommand(mySQLString, myConnection)
myCommand.ExecuteNonQuery()
PictureBox1.Image = Nothing
TextBoxPictureFilePath.Text = ""
Catch ex As Exception
MessageBox.Show(ex.Message & " - " & ex.Source)
End Try
Run the application, it should work as desired.

Adding data from Text boxes directly to database and viewing updated gridview

still very new to this and can't seem to find exactly what I'm looking for. Quick run-through on what I'm trying to accomplish. I have a datagridview (3 columns - Id, Name, Address) that is connected to a local .mdf database file, that I'm able to search through using a search textbox. My goal NOW is to submit records into the database directly using 2 text fields and the Id field to automatically increment. (Id++, txtName.Text, txtAddress.Text) and to use a send button(btnSend) to activate this event.(PLEASE KEEP IN MIND, MY GOAL IS TO HAVE EVERYONE INCLUDING THE NEW RECORD SHOW UP IN THE DATAGRIDVIEW AND FOR THE NEW ROW TO BE INSERTED DIRECTLY TO THE DATABASE AND SAVE ANY CHANGES) I've been hammering at this for a couple days now and would appreciate any help. Below is my code, but please keep in mind I'm still new and trying to figure this language out so if there's any unnecessary code, please do let me know... Also if you want to help with one additional thing, maybe some code on how to export that table to a different file from an export button. Thanks! I'm currently also getting an error saying "Cannot find table 0." when I click the btnSend button.
Public Sub btnSend_Click(ByVal sender As Object, e As EventArgs) Handles btnSend.Click
Try
Dim connectionString As String
Dim connection As SqlConnection
Dim ds As New DataSet("Table")
Dim dataset As New DataSet()
Dim sqlInsert As String
Dim sqlSelect As String
Dim Id As Integer = 5
Dim newRow As DataRow = dataset.Tables(0).NewRow()
connectionString = "Data Source=(LocalDB)\v11.0;AttachDbFilename=""" & My.Application.Info.DirectoryPath & "\Database1.mdf"";Integrated Security=True;"
sqlInsert = "INSERT INTO Table (#Id, #Name, #Address) VALUES (" & Id & ", '" & txtName.Text & "','" & txtAddress.Text & "')"
sqlSelect = "SELECT * FROM Table"
connection = New SqlConnection(connectionString)
Dim da As New SqlDataAdapter()
connection.Open()
da.Fill(ds)
Using da
da.SelectCommand = New SqlCommand(sqlSelect)
da.InsertCommand = New SqlCommand(sqlInsert)
da.InsertCommand.Parameters.Add(New SqlParameter("Id", SqlDbType.Int, 4, Id))
da.InsertCommand.Parameters.Add(New SqlParameter("Name", SqlDbType.NText, 50, txtName.Text))
da.InsertCommand.Parameters.Add(New SqlParameter("Address", SqlDbType.NText, 50, txtAddress.Text))
Using dataset
da.Fill(dataset)
newRow("Id") = Id
newRow("Name") = txtName.Text
newRow("Address") = txtAddress.Text
dataset.Tables(0).Rows.Add(newRow)
da.Update(dataset)
End Using
Using newDataSet As New DataSet()
da.Fill(newDataSet)
End Using
End Using
connection.Close()
Catch ex As Exception
MsgBox(ex.Message)
Throw New Exception("Problem loading persons")
End Try
Dim updatedRowCount As String = gvDataViewer.RowCount - 1
lblRowCount.Text = "[Total Row Count: " & updatedRowCount & "]"
End Sub

Updating Image file in database using MS Access

Here is my code
Dim Cmd As New OleDbCommand
Dim strsql As String
Try
Dim fsreader As New FileStream(OpenFile.FileName, FileMode.Open, FileAccess.Read)
Dim breader As New BinaryReader(fsreader)
Dim imgbuffer(fsreader.Length) As Byte
breader.Read(imgbuffer, 0, fsreader.Length)
fsreader.Close()
strsql = "UPDATE AccResult SET (PicFile, PicName) Values (#pfile, #pname) WHERE StudNo = '" & Form1.sNo.Text & "'"
Cmd = New OleDbCommand(strsql, con)
Cmd.Parameters.AddWithValue("#pfile", txtSave.Text)
Cmd.Parameters.AddWithValue("#pname", imgbuffer)
Cmd.ExecuteNonQuery()
Cmd.Dispose()
Catch ex As Exception
End Try
please help me how can i update the students data when saving their picture in database. im using VB.NET. Thank You.
Looks like simple error in your logic - you have the filename reversed with the file content
Cmd.Parameters.AddWithValue("#pfile", txtSave.Text)
Cmd.Parameters.AddWithValue("#pname", imgbuffer)
Should be
Cmd.Parameters.AddWithValue("#pfile", imgbuffer)
Cmd.Parameters.AddWithValue("#pname", txtSave.Text)