I am trying to update a blob field based on id, with the following code but it always insert Null.
Private Sub Button5_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button5.Click
openconnection()
Dim cmd As New Odbc.OdbcCommand("UPDATE blob_table SET image=#PictureBox1 WHERE id='6'", myconnection)
Dim fs As New System.IO.FileStream("E:\Untitled.png", IO.FileMode.Open, IO.FileAccess.Read)
Dim b(fs.Length() - 1) As Byte
fs.Read(b, 0, b.Length)
fs.Close()
Dim P As Odbc.OdbcParameter = New Odbc.OdbcParameter("#PictureBox1", Odbc.OdbcType.Image, b.Length, ParameterDirection.Input, True, 0, 0, Nothing, DataRowVersion.Current, b)
cmd.Parameters.Add(P)
openconnection()
cmd.ExecuteNonQuery()
closeconnection()
End Sub
I check the connection, it is properly working,
The image path is a valid path. anyone can help me to find the mistake in the query?
I think you need to set the value of #PictureBox1 to a byte array - e.g. byte[] as I understand that's what the image blob type maps to instead of byte.
Try using a BinaryReader to populate your b byte array:
something like:
Dim b As Byte()
Dim br As New BinaryReader(fs)
b = br.ReadBytes(CInt(fs.Length))
br.Close()
fs.Close()
you have to do something like this to insert image to DB
Using pgFileStream As FileStream = New FileStream(productImageFilePath, FileMode.Open, FileAccess.Read)
Using pgReader As BinaryReader = New BinaryReader(New BufferedStream(pgFileStream))
Dim pgByteA As Byte() = pgReader.ReadBytes(CInt(pgFileStream.Length))
command.CommandText = " update gtab82 set memphoto=#Image where memuuid ='" & txtmemuid.Text & "' "
command.Parameters.AddWithValue("#Image", pgByteA)
command.ExecuteNonQuery()
End Using
End Using
am using PostgreSQL databse and my image field is bytea
Related
I know that there are already a couple of questions which seems like my problem but I tried to copy a lot of it and tried but can’t get the resold I want.
Actually is my target to save an image from a Picture Box as Byte() into mySQL Database.
At first I tried the simple way like
Dim acCust As Image = pgbox.image
Dim picBytes() As Byte
Using ms As New MemoryStream
cust.Save(ms, cust.RawFormat)
picBytes = ms.ToArray()
End Using
but with this I run into a general GUI error so I copied the Picture at first like this
Dim rec As New Rectangle(0, 0, acCust.Width, acCust.Height)
Dim mus As New ImageFormatConverter
Dim muster As New Bitmap(rec.Width, rec.Height)
Dim cust As Image
Using grp = Graphics.FromImage(muster)
grp.DrawImage(acCust, New Rectangle(0, 0, rec.Width, rec.Height), rec, GraphicsUnit.Pixel)
cust = muster
End Using
If I use after that again the code
Dim picBytes() As Byte
Using ms As New MemoryStream
cust.Save(ms, cust.RawFormat)
picBytes = ms.ToArray()
End Using
sqlconection.Open()
Dim query As String = "INSERT INTO tblimg(img) VALUES ('#image');"
Dim com As New MySqlCommand(query, sqlconection)
com.Parameters.AddWithValue("image", picBytes)
com.ExecuteNonQuery()
sqlconection.Close()
everything looks sofa ok but if I read it like this
Dim imgData As Byte()
Dim sql As String = "SELECT img FROM tblimg"
sqlconection.Open()
Dim cmd As New MySqlCommand(sql, sqlconection)
Using rdr As MySqlDataReader = cmd.ExecuteReader
If rdr.HasRows Then
rdr.Read()
imgData = TryCast(rdr.Item("img"), Byte())
' in case this record has no image
If imgData IsNot Nothing Then
' ToDo: dispose of any previous Image
' create memstream from bytes
Using ms As New MemoryStream(imgData)
' create image from stream, assign to PicBox
pbbox.Image = CType(Image.FromStream(ms), Image)
End Using
End If
End If
End Using
I got an alarm message
Eine nicht behandelte Ausnahme des Typs "System.ArgumentException" ist in System.Drawing.dll aufgetreten.
Zusätzliche Informationen: Ungültiger Parameter.
(Sorry it's in German)
Has anybody an idea what and were it’s going wrong?
If I use the the picByts () in a new memory stream and convert it back to an image then I got the correct result. It seems like there is a problem with the up or download query
in my Server I use the variable type LongBlob
You save a Byte array to a database in exactly the same way as you save any other data. You write your SQL, you add a parameter to a command and you set its value. This:
Dim query As String = "INSERT INTO tblimg(img) VALUES ('#image');"
Dim com As New MySqlCommand(query, sqlconection)
com.Parameters.AddWithValue("image", picBytes)
is wrong. You only wrap literal strings in single quotes in SQL code. That should be like this:
Dim query As String = "INSERT INTO tblimg(img) VALUES (#image);"
Dim com As New MySqlCommand(query, sqlconection)
com.Parameters.AddWithValue("#image", picBytes)
No single quotes around the parameter in the SQL and use the actual parameter name when adding it to the command. I'd also recommend using Add rather than AddWithValue but that's a discussion for another time.
I want to insert an image into my SQL database. I have this code currently and it is entering a Null where the image should be. Why is this occurring?
I'm using here a simple addquestion Class.
You can find the code I used bellow :
Imports System.IO
Imports System.Data.SqlClient
Public Class addquestion
Dim con As New System.Data.Odbc.OdbcConnection("DRIVER={MySQL ODBC 5.2 ANSI Driver};SERVER=localhost;PORT=3306;DATABASE=physicsapp;USER=root;PASSWORD=root;OPTION=3;")
Dim rs As Odbc.OdbcDataReader
Private Sub addquestion_Load(sender As Object, e As EventArgs) Handles MyBase.Load
End Sub
Private Sub QuestionButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles QuestionButton.Click
Dim myFileDlog As New OpenFileDialog
myFileDlog.InitialDirectory = "c:/"
myFileDlog.Filter = "All Files (*.*)|*.*" & _"|Picture Files (*.png)|*.png"
myFileDlog.FilterIndex = 1
myFileDlog.RestoreDirectory = True
If myFileDlog.ShowDialog() = _
DialogResult.OK Then
If Dir(myFileDlog.FileName) <> "" Then
MsgBox("File Exists: " & _
myFileDlog.FileName, _
MsgBoxStyle.Information)
Else
MsgBox("File Not Found", _
MsgBoxStyle.Critical)
End If
End If
qnametextbox.Text = myFileDlog.FileName
End Sub
Dim ans as Char = "B"
Dim file As String = qnametextbox.Text
Dim question As Image
question = Image.FromFile(file)
Dim ms As New MemoryStream()
question.Save(ms, System.Drawing.Imaging.ImageFormat.Png)
Dim data As Byte() = ms.GetBuffer()
Dim s As String = "INSERT INTO tests VALUES (#Question ,'" & ans & "', 200)"
Dim sql As New Odbc.OdbcCommand(s, con)
sql.Parameters.Add("#Question", Odbc.OdbcType.VarBinary).Value = data
con.Open()
sql.ExecuteNonQuery()
con.Close()
this is the definition of the table
CREATE TABLE `tests` (
`Question` blob NOT NULL,
`CorrectAnswer` varchar(8) DEFAULT NULL,
`QuestionNumber` int(8) NOT NULL AUTO_INCREMENT,
KEY `QuestionNumber` (`QuestionNumber`)
) ENGINE=MyISAM AUTO_INCREMENT=201 DEFAULT CHARSET=utf8
Any suggestion can help.
Thanks.
Regardless of what data access technology or database you use, you need to convert am Image to a Byte first and then save that. On retrieval, you convert the Byte array back to an Image.
To save:
Dim connection As New SqlConnection("connection string here")
Dim command As New SqlCommand("UPDATE MyTable SET Picture = #Picture WHERE ID = 1", connection)
'Create an Image object.'
Using picture As Image = Image.FromFile("file path here")
'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.Add("#Picture", SqlDbType.VarBinary).Value = stream.GetBuffer()
End Using
End Using
connection.Open()
command.ExecuteNonQuery()
connection.Close()
I need to get all the values of each record in a table, this is so I can then add them to a text file log, a record per line, and then delete them from the database. I'm new to this and have searched how to add SQL query results to an array or a generic list, but I don't fully understand them.
All I have so far is:
Private Sub btnClearAll_Click(sender As Object, e As EventArgs) Handles btnClearAll.Click
conn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=E:\Application Programming\Project\Issue Logger\Database\IssueLoggerDB.accdb"
Dim strSQl = "TRUNCATE TABLE CurrentJobs"
Dim commandInsert As New OleDbCommand
commandInsert.CommandText = strSQl
commandInsert.Connection = conn
commandInsert.Connection.Open()
commandInsert.ExecuteNonQuery()
Me.ReportViewer1.RefreshReport()
End Sub
This is for a Uni project, and above is how we have been to shown to do it, however nothing I have found while researching looks similar.
Feel free to use this procedure:
Private Sub DataTableToTextFile()
Dim connString As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=E:\Application Programming\Project\Issue Logger\Database\IssueLoggerDB.accdb"
Using conn As OleDbConnection = New OleDbConnection(connString)
Dim dt As New DataTable
conn.Open()
'Change the query. It's not a good practice to use '*' in your select queries. Please, use the column names instead.
Dim dataAdapter As New OleDbDataAdapter("SELECT * FROM CurrentJobs", conn)
dataAdapter.Fill(dt)
'Change the path to your desired path
Dim exportPath As String = "C:\Logs\"
Dim exportFileName As String = "log.txt"
'If directory does not exists, create it
If Not Directory.Exists(exportPath) Then
Directory.CreateDirectory(exportPath)
End If
'Write data into the text file
Dim writer As New StreamWriter(exportPath + exportFileName)
Try
Dim sb As New StringBuilder
For Each row As DataRow In dt.Rows
sb = New StringBuilder
For Each col As DataColumn In dt.Columns
sb.Append(row(col.ColumnName))
Next
writer.WriteLine(sb.ToString())
Next
Catch ex As Exception
Throw ex
Finally
If Not writer Is Nothing Then writer.Close()
End Try
'Finally clean database table
Dim strSQl = "Delete From CurrentJobs"
Dim commandDelete As New OleDbCommand(strSQl, conn)
'execute
commandDelete.ExecuteNonQuery()
'close connection
conn.Close()
End Using
End Sub
when i try to select an item in the ListView that has no image in my database this error shows Unable to cast object of type 'System.DBNull' to type 'System.Byte[]'. i tried to put up some code like isDBNull or DBNull but it's applicable.
here's my code:
Private Sub LvPeople_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles LvPeople.SelectedIndexChanged
If LvPeople.SelectedItems.Count > 0 Then
Dim connstring As String = "server = localhost; user id = root; database = db; password = root"
Dim Sql As String = "select * from candidate where idn='" & LvPeople.SelectedItems(0).Text & "'"
Dim conn As New MySqlConnection(connstring)
Dim cmd As New MySqlCommand(Sql, conn)
Dim dr As MySqlDataReader = Nothing
conn.Open()
dr = cmd.ExecuteReader()
dr.Read()
Dim imagebytes As Byte() = CType(dr("photo"), Byte())
Using ms As New IO.MemoryStream(imagebytes)
PictureBox1.Image = Image.FromStream(ms)
PictureBox1.SizeMode = PictureBoxSizeMode.StretchImage
End Using
conn.Close()
End If
End Sub
End Class
the error points here:
Dim imagebytes As Byte() = CType(dr("photo"), Byte())
i really have no idea what to put here. just a newbie here.
Since it is possible that there is no image data previously saved for a row, you need to test for DBNull before trying to use it:
If IsDBNull(dr("photo")) = False Then
Dim imagebytes As Byte() = CType(dr("photo"), Byte())
Using ms As New IO.MemoryStream(imagebytes)
PictureBox1.Image = Image.FromStream(ms)
PictureBox1.SizeMode = PictureBoxSizeMode.StretchImage
End Using
Else
' maybe display a "no Photo Available" stock image
End If
Note that this DBNull test is different than the one Steve is using. IsDBNull is a language function while the one he is using is a method of the DataReader object, which is also why there are different requirements. Yet a third way would be to compare it to System.DbNull:
If DBNull.Value.Equals(dr("photo")) = False Then
...
End If
Use the DataReader method IsDBNull, but this method requires the position of the field in the IDataRecord used by the reader, so you need to call also GetOrdinal with the name of the field to check
(Links point to the Sql Server version but they are the same for MySql)
Private Sub LvPeople_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles LvPeople.SelectedIndexChanged
If LvPeople.SelectedItems.Count > 0 Then
Dim connstring As String = "...."
Dim Sql As String = "select * from candidate where idn=#id"
Using conn = new MySqlConnection(connstring)
Using cmd = new MySqlCommand(Sql, conn)
conn.Open()
cmd.Parameters.AddWithValue("#id", LvPeople.SelectedItems(0).Text)
Using dr = cmd.ExecuteReader()
if dr.Read() Then
if Not dr.IsDbNull(dr.GetOrdinal("photo")) Then
Dim imagebytes As Byte() = CType(dr("photo"), Byte())
Using ms As New IO.MemoryStream(imagebytes)
PictureBox1.Image = Image.FromStream(ms)
PictureBox1.SizeMode = PictureBoxSizeMode.StretchImage
End Using
End If
End If
End Using
End Using
End Using
End If
End Sub
Could anyone help me with the following WHERE statement ? I want to make bn as reference in WHERE statement.
This is whats in my code:
Public bn As String = ""
Dim SQLStatement As String = "UPDATE patient SET number_of_bottles='" & lblBottle.Text & "' WHERE bednumber=bn ORDER BY patient_ID DESC LIMIT 1"
During the program, bn is an identifier where I would know which bednumber I will gonna access.
Any help would be appreciated thanks!
(Edited to use MySQL-specific objects rather than generic ODBC)
Dim bn As String = "" ' Set this to some value in your code
Dim bottles As Integer = 0 ' Set this to some value in your code
Dim SQLStatement As String = "UPDATE patient SET number_of_bottles = #bottles WHERE bednumber = #bednumber"
Using cnn As New MySqlConnection("Connection string here")
Dim cmd As New MySqlCommand(SQLStatement, cnn)
cmd.Parameters.AddWithValue("bottles", bottles)
cmd.Parameters.AddWithValue("bednumber", bn)
cnn.Open()
cmd.ExecuteNonQuery()
cnn.Close()
End Using
Alternate version, creating MySqlParameter objects by hand -- note that you'll need to create the parameter objects, set their values, then add them to the parameters collection of the MySqlCommand object
Using cnn As New MySqlConnection("Connection string here")
Dim cmd As New MySqlCommand(SQLStatement, cnn)
Dim pBottles As New MySqlParameter("bottles", bottles)
Dim pBedNumber As New MySqlParameter("bednumber", bn)
cmd.Parameters.Add(pBottles)
cmd.Parameters.Add(pBedNumber)
cnn.Open()
cmd.ExecuteNonQuery()
cnn.Close()
End Using