I have been trying to figure out how to submit PDF files into a MYSQL database via my VB.NET project, so far I have only been able to figure out how to insert image files into the MYSQL but I'm not sure how to translate this code to support PDF files rather than images.
The code below shows how to browse an image and display it.
Try
Dim OFD As FileDialog = New OpenFileDialog()
OFD.Filter = "Image File (*.jpg;*.bmp;*.gif)|*.jpg;*.bmp;*.gif"
If OFD.ShowDialog() = DialogResult.OK Then
imgpath = OFD.FileName
PictureBox1.ImageLocation = imgpath
End If
OFD = Nothing
Catch ex As Exception
MsgBox(ex.Message.ToString())
End Try
The code below this shows the insertion of the image files into the MYSQL database once an image has been chosen.
Try
Dim mstream As New System.IO.MemoryStream()
PictureBox1.Image.Save(mstream, System.Drawing.Imaging.ImageFormat.Jpeg)
arrImage = mstream.GetBuffer()
Dim FileSize As UInt32
FileSize = mstream.Length
mstream.Close()
conn.ConnectionString = Myconnection
conn.Open()
sql = "insert into studentsubmissions(content, submissionid, studentnumber, time, date, deadline, title, work, modulename) VALUES (#filestuff, #subid, #stunumber, #subtime, #subdate, #workdeadline, #stutitle, #stuwork, #workmodulename)"
cmd.Connection = conn
cmd.CommandText = sql
cmd.Parameters.AddWithValue("#filestuff", arrImage)
cmd.Parameters.AddWithValue("#subid", idbox.Text)
cmd.Parameters.AddWithValue("#stunumber", usernameconstant.Text)
cmd.Parameters.AddWithValue("#subtime", todaystime.Text)
cmd.Parameters.AddWithValue("#subdate", todaysdate.Text)
cmd.Parameters.AddWithValue("#workdeadline", deadlinesubmission.Text)
cmd.Parameters.AddWithValue("#stutitle", titlesubmission.Text)
cmd.Parameters.AddWithValue("#stuwork", workload.Text)
cmd.Parameters.AddWithValue("#workmodulename", modulename.Text)
cmd.ExecuteNonQuery()
MessageBox.Show("Created")
cmd.Parameters.Clear()
conn.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
Below this is the method of displaying a PDF file on an Adobe PDF Reader in my project which is what I eventually want replacing the first set of code in displaying the documents and making the second set of code shown to support this.
Dim opf As New OpenFileDialog
opf.Filter = "PDF File | *.pdf"
If opf.ShowDialog = DialogResult.OK Then
AxAcroPDF1.src = opf.FileName
text_file.Text = opf.SafeFileName
End If
Related
I'm having trouble updating images into my database in MySQL.
I'm using a combobox to select a user ID and populate that combobox with that ID and the image that's associated with that ID on a picturebox
I can add and remove images just fine, but the problem is when I try to update any image i get the error " Unable to cast object of type 'System.Byte[]' to type 'System.IConvertible' ".
I've looked it up and it has something to do with passing an array of bytes to a single byte, which is not possible.
Here's my code to update the image:
Dim filesize As UInteger
Dim imgcliente As New MemoryStream
PictureBox1.Image.Save(imgcliente, PictureBox1.Image.RawFormat)
Dim arrImage As Byte() = imgcliente.GetBuffer
filesize = imgcliente.Length
imgcliente.Close()
And here's my code to retrive the associated image from the ID:
cmd = New MySqlCommand("SELECT Imagem_Cliente FROM adegages.clientes WHERE ID_Cliente='" & cmb_cliente.Text & "'", con)
Dim imagedata As Byte() = DirectCast(cmd.ExecuteScalar(), Byte())
If Not imagedata Is Nothing Then
Using ms As New System.IO.MemoryStream(imagedata, 0, imagedata.Length)
ms.Write(imagedata, 0, imagedata.Length)
PictureBox1.Image = New Bitmap(Image.FromStream(ms, True))
End Using
End If
It's probably just some line and it may be incredibly ease to solve, but I just can't seem to figure out where I'm wrong.
Thx in advance
Edit:
This is the code to edit records to the database
Dim atualizar_vendas As New MySqlCommand("UPDATE vendas SET ID_Venda=#ID,
Cliente_Venda=#CLIENTE, Data_Venda=#DATA, Qnt_Vinho_Venda=#QNT,
Tipo_Casta_Venda=#TIPO_CASTA, Nome_Casta_Venda=#NOME_CASTA,
Total_Venda=#TOTAL, Imagem_Cliente=#IMG WHERE ID_Venda = #ID", con)
atualizar_vendas.Parameters.Add("#ID", MySqlDbType.Int32).Value = txt_id_venda.Text
atualizar_vendas.Parameters.Add("#CLIENTE", MySqlDbType.VarChar).Value = cmb_cliente.Text
atualizar_vendas.Parameters.Add("#DATA", MySqlDbType.VarChar).Value = mtx_data_venda.Text
atualizar_vendas.Parameters.Add("#QNT", MySqlDbType.VarChar).Value = txt_qnt_vendida.Text
atualizar_vendas.Parameters.Add("#TIPO_CASTA", MySqlDbType.VarChar).Value = cmb_tipo_casta.Text
atualizar_vendas.Parameters.Add("#NOME_CASTA", MySqlDbType.VarChar).Value = cmb_nome_casta.Text
atualizar_vendas.Parameters.Add("#TOTAL", MySqlDbType.VarChar).Value = txt_total.Text
atualizar_vendas.Parameters.Add("#IMG", MySqlDbType.Int32).Value = arrImage
Try
con.Open()
If atualizar_vendas.ExecuteNonQuery() > 0 Then
MsgBox("Editado com sucesso!", MsgBoxStyle.Information, "AdegaGes")
Limpar()
End If
con.Close()
Retrieve_Clientes()
Retrieve_Tipo_Casta()
Catch ex As Exception
MsgBox(ex.Message, MsgBoxStyle.Critical, "AdegaGes")
con.Close()
Finally
con.Dispose()
cmd.Dispose()
End Try
Take a look at this:
atualizar_vendas.Parameters.Add("#IMG", MySqlDbType.Int32).Value = arrImage
That parameter is asking for a single integer, instead of a byte array. You probably want MySqlDbType.Blob there instead.
Actually i'm trying to create a program in VB.NET that get xml files from a folder and set it's data to MySQL.
Each XML file has unique ID for which is created a database and all tables.
In the folder i can have files like "DC_001" "DF_001" "DC_002" and that's mean that the data from the XML file DC_001 have to be placed in database 001 in table DC.
Actually i've made the method which create the database for each unique ID and it's tables but as i'm not very in to VB.NET i need some suggestion on how to put the data inside the XML to each database.
Here is my method where i create the database and tables.
Dim PIVA As New ArrayList
Dim conn As MySqlConnection = New MySqlConnection
conn.ConnectionString = "server=127.0.0.1;user id=root; password=block; database=mysql"
For Each fileName As String In Directory.EnumerateFileSystemEntries("C:\Users\imytyuk\Desktop\test")
Dim file As String = Trim(EstrCampo("_", fileName, 1, 2))
If Not PIVA.Contains(file) Then
PIVA.Add(file)
End If
Next
For Each iva In PIVA
Dim cmd As MySqlCommand = New MySqlCommand("CREATE DATABASE `" & iva & "`", conn)
Try
conn.Open()
Try
cmd.ExecuteNonQuery()
Catch ex As Exception
End Try
conn.Close()
CreaTB(iva)
Catch
End Try
Next
While here is like a XML file can be structured
UPDATE:
I'm trying to use the following method to insert the data from XML but i get ""Column count doesn't match value count at row 1"}" as Exception.
Here is the code:
Sub AddXML()
For Each fileName As String In Directory.EnumerateFileSystemEntries("C:\Users\imytyuk\Desktop\test")
databaseFilePut(fileName, "datacollect", Trim(EstrCampo("_", fileName, 1, 2)))
File.Delete(fileName)
Next
End Sub
Public Shared Sub databaseFilePut(ByVal varFilePath As String, ByVal table As String, ByVal db As String)
Dim file() As Byte
Dim stream = New FileStream(varFilePath, FileMode.Open, FileAccess.Read)
Dim reader = New BinaryReader(stream)
file = reader.ReadBytes(CType(stream.Length, Integer))
Dim conn As MySqlConnection = New MySqlConnection
conn.ConnectionString = "server=127.0.0.1;user id=root; password=block; database=" & db
Dim cmd As MySqlCommand = New MySqlCommand("INSERT INTO " & table & " Values(#File)", conn)
Try
conn.Open()
cmd.Parameters.Add("#File", MySqlDbType.VarBinary, file.Length).Value = file
cmd.ExecuteNonQuery()
Catch ex As Exception
End Try
End Sub
I have successfully saved a pdf file to my database (MySQL) as a longblob and used this code :
opf.Filter = "PDF FILES |*.pdf"
If opf.ShowDialog = Windows.Forms.DialogResult.OK Then
//Display the PDF you want to save in the PDFVIEWER
pdfview.src = opf.FileName
Dim Mystream As New FileStream(opf.FileName, FileMode.Open)
Dim filesize As Long = Mystream.Length
Dim buffer(filesize) As Byte
Mystream.Read(buffer, 0, filesize)
//Save the pdf file to the database
Dim query As String = "insert into sample(pdfnaho)values(#file)"
Dim cmd As New MySqlCommand(query, con)
con.Open()
cmd.Parameters.AddWithValue("#file", buffer)
cmd.ExecuteNonQuery()
MsgBox("SAVED!")
con.Close()
End If
Then I used this code for displaying but It doesn't work and I don't know what to do :
Dim query As String = "select * from sample where id = 1"
Dim cmd As New MySqlCommand(query, con)
con.Open()
Dim dr As MySqlDataReader = cmd.ExecuteReader
While dr.Read
If dr.HasRows Then
pdfview.src = dr.GetString("pdfnaho")
End If
End While
con.Close()
How should I display my saved pdf file from database? Thank You
I can not put this as a comment because I don't have enough reputation.
What PDF viewer are you using?. If it is the Adobe PDF Viewer I am almost sure (from previous research for another project) that you can not stream into it.
This is an example from my previous project, I modified it to fit yours, make sure to edit the query to fit your table and columns names.
You have to ran a query that return only the cell with the file in binary.
Dim query as String = "SELECT file_content FROM sample WHERE ID=1;"
Public Sub OpenPDF()
If File.Exists(Application.StartupPath() & "\temp.file") = True Then
pdfview.src = "blank.pdf"
My.Computer.FileSystem.DeleteFile(Application.StartupPath() & "\temp.file")
End If
Dim cmd As New MySqlCommand(query, con)
Dim Buffer As Byte()
con.open()
Buffer = cmd.ExecuteScalar
con.close()
File.WriteAllBytes(Application.StartupPath() & "\temp.file", Buffer)
pdfview.src = Application.StartupPath() & "\temp.file"
End Sub
With this example, the code will check if there is an existing "temp.file" and delete it, then load nothing on the pdfviewer to clear whatever is displaying.
The the database connection, get the data, store it on a file then display it with the pdfviewer.
I've been attempting to adapt part of this procedure that I found online (can't remember where now!). I've been trying to use this to upload images to a MYSQL database using BLOB data type.
Public Sub SQLUpload()
Dim connection As New MySqlConnection(ConnectionImage)
Dim command As New MySqlCommand("INSERT INTO Images (File, FileName, FileSize) VALUES (#Picture, 'Name1', 'Size1')", connection)
'Create an Image object.'
Using picture As Image = Image.FromFile("C:\DIR\Pictures\Person.jpg")
'Create an empty stream in memory.'
Using stream As New IO.MemoryStream
'Fill the stream with the binary data from the Image.'
picture.Save(Stream, Imaging.ImageFormat.Jpeg)
'Get an array of Bytes from the stream and assign to the parameter.'
command.Parameters.AddWithValue("#Picture", SqlDbType.VarBinary).Value = stream.GetBuffer()
End Using
End Using
connection.Open()
Try
command.ExecuteNonQuery()
Catch ex As Exception
MsgBox(ex.ToString)
End Try
connection.Close()
End Sub
Above is the current sub routine. Whenever this is executed, the routine operates fine until it gets to:
Command.ExecuteNonQuery()
It throws the error:
Unable to cast object of type System.Byte[] to type System.IConvertible
I'm pretty sure this happens because of the fact that the bytes from the image are returned as an array however the memory that they are saved to does not support an array? This was just gathered from reading I've done elsewhere online.
However, as this is not all my code I am frankly not sure what the problem is. Can anyone see what is wrong with it?
Many Thanks
Where you have
SqlDbType.VarBinary ' <-- this is Sql Server DB type
use
MySqlDbType.Blob
Like this
Dim file() As Byte = ' set your file
Dim p As MySqlParameter = new MySqlParameter("#Picture", MySqlDbType.Blob, file.Length)
p.Value = file
command.Parameters.Add(p)
As it mentioned by others, you don't need to "Save" your file - just read it into byte array. My code would look something like below:
Public Sub SQLUpload()
Try
Using conn As New MySqlConnection(connString)
' Parametarize entire sql string
Dim sql As String =
"INSERT INTO Images (File, FileName, FileSize) VALUES (#Picture, #name, #size)"
Using cmd As New MySqlCommand(sql, conn)
Dim fileName As String = "C:\DIR\Pictures\Person.jpg"
Dim file() As Byte = File.ReadAllBytes(fileName)
cmd.Parameters.AddWithValue("#Picture", MySqlDbType.Blob).Value = file
cmd.Parameters.AddWithValue("#file", MySqlDbType.VarChar).Value = fileName
cmd.Parameters.AddWithValue("#size", MySqlDbType.Int32).Value = file.Length
conn.Open()
cmd.ExecuteNonQuery()
End Using
End Using
MessageBox.Show("Success")
Catch ex As Exception
MessageBox.Show(ex.ToString())
End Try
End Sub
I have stored Image as blob in mysql,And now I want ti display this image in picturebox in Vb,
I used Following code..
Dim con As New MySqlConnection
Dim str As String = "host=localhost;userid=root;password=;database=new;"
Dim qry As String = "select pic from img where id='1'"
Dim cmd As MySqlCommand
Dim reader As MySqlDataReader
Dim dt() As Byte
con.ConnectionString = str
Try
con.Open()
MsgBox(con.State)
cmd = New MySqlCommand(qry, con)
reader = cmd.ExecuteReader()
reader.Read()
dt = reader.Item("pic")
Dim mstream As New System.IO.MemoryStream
PictureBox1.Image = Image.FromStream(mstream)
reader.Close()
Catch ex As Exception
MsgBox(ErrorToString)
End Try
It shows connection state=1
but gives error Saying"Parameter is not valid,Whats wrong?"
You're creating a MemoryStream but not writing any data to it. The image data isn't going to magically come out of the stream; you have to put it there first. Have you done any reading on the MemoryStream class? If you have then you know that it has a constructor that allows you to pass in a Byte array. You have a Byte array containing the image data so that's a match made in heaven.
Also, make sure that you dispose the MemoryStream after using it.