i have tried this code here to insert and show picture from database to picturebox : stackoverflow.com/questions/5624760/store-picture-to-database-retrieve-from-db-into-picturebox
and yeah, it is working , but when i tried to do update using the same syntax as insert it got this error :
this is the insert syntax i use :
Dim FileSize As UInt32
Dim mstream As New System.IO.MemoryStream()
gambar.Image.Save(mstream, System.Drawing.Imaging.ImageFormat.Jpeg)
Dim arrImage() As Byte = mstream.GetBuffer()
FileSize = mstream.Length
mstream.Close()
call konek
strSQL = "insert into tbmahasiswa VALUES ('" & _
txtNIM.Text & "','" & _
txtNama.Text & "','" & _
Format(dtpTanggal.Value, "yyyy-MM-dd") & "','" & _
txtAlamat.Text & "','" & _
cboJurusan.Text & "',#gambar)"
com = New MySql.Data.MySqlClient.MySqlCommand(strSQL, conn)
With com
.Parameters.AddWithValue("#gambar", arrImage)
.ExecuteNonQuery()
End With
and this the code i use to show picture from database to picture box :
Dim imgData As Byte()
call konek
strSQL = "select * from tbMahasiswa where NIM ='" & txtNIM.Text & "'"
com = New MySql.Data.MySqlClient.MySqlCommand(strSQL, conn)
Using rd = com.ExecuteReader
rd.Read()
If rd.HasRows Then
txtNama.Text = rd.Item(1)
dtpTanggal.Value = rd.Item(2)
txtAlamat.Text = rd.Item(3)
imgData = TryCast(rd.Item(5), Byte())
If imgData IsNot Nothing Then
Using ms As New MemoryStream(imgData)
gambar.Image = CType(Image.FromStream(ms), Image)
End Using
End If
End If
End Using
Both Insert and Retrieving Picture Code above is Working ! , and then i use this code for update :
Dim FileSize As UInt32
Dim mstream As New System.IO.MemoryStream()
gambar.Image.Save(mstream, System.Drawing.Imaging.ImageFormat.Jpeg)
Dim arrImage() As Byte = mstream.GetBuffer()
FileSize = mstream.Length
mstream.Close()
call konek
strSQL = "update tbmahasiswa set Nama ='" & txtNama.Text & _
"', TglLahir ='" & Format(dtpTanggal.Value, "yyyy-MM-dd") & _
"', Alamat ='" & txtAlamat.Text & _
"', Jurusan ='" & cboJurusan.Text & _
"', gambar =' #gambar" & _
"' where NIM ='" & txtNIM.Text & "'"
com = New MySql.Data.MySqlClient.MySqlCommand(strSQL, conn)
With com
.Parameters.AddWithValue("#gambar", arrImage)
.ExecuteNonQuery()
End With
and then i got the error like in the picture above, all other data is correctly saved except the picture, it become some unknown file blob 8 KB size.
i'm still newbie at insert , update, delete picture in VB, please can you tell me what is wrong with the Update syntax code , is it already true but i'm missing something ? or is it totally wrong with the syntax ? please i need your guide here...
UPDATE :
actually there is "call konek" above "STRSQL" in the code, "konek" have the code for open the mysql connection,i put it in the separate module, here the full code in my module :
Module modKoneksi
Public conn As New MySql.Data.MySqlClient.MySqlConnection
Public rd As MySql.Data.MySqlClient.MySqlDataReader
Public com As MySql.Data.MySqlClient.MySqlCommand
Public strSQL As String
Public Sub konek()
conn.Close()
strSQL = "server='localhost';user='root';pwd='';database='dbsekolah';"
Try
conn.ConnectionString = strSQL
conn.Open()
Catch ex As MySql.Data.MySqlClient.MySqlException
MsgBox(ex.Message)
End
End Try
End Sub
End Module
hope this makes you easier to solve my problem
I know its late but this is the working code for me :
For retrieving the record from database with pictures :
Call konek() 'Call the connection module'
strSQL = "select * from tbMahasiswa where ID ='" & txtID.Text & "'"
com = New MySql.Data.MySqlClient.MySqlCommand(strSQL, conn)
Using rd = com.ExecuteReader
rd.Read()
If rd.HasRows Then
txtNIM.Text = rd.Item(1)
txtNama.Text = rd.Item(2)
dtpTanggal.Value = rd.Item(3)
txtAlamat.Text = rd.Item(4)
imgData = TryCast(rd.Item(6), Byte())
If imgData IsNot Nothing Then
Using ms As New MemoryStream(imgData)
gambar.Image = CType(Image.FromStream(ms), Image)
End Using
End If
cboJurusan.SelectedIndex = cboJurusan.FindStringExact(rd.Item(5))
End If
End Using
For inserting record to database with pictures :
Call konek()
strSQL = "Insert Into tbmahasiswa Values ('" & txtID.Text & _
"','" & txtNIM.Text & _
"','" & txtNama.Text & _
"','" & Format(dtpTanggal.Value, "yyyy-MM-dd") & _
"','" & txtAlamat.Text & _
"','" & cboJurusan.Text & _
"',#gambar)"
com = New MySql.Data.MySqlClient.MySqlCommand(strSQL, conn)
With com
If opdGambar.FileName = Nothing Then 'opdGambar is a PictureBox name'
.Parameters.Add(New MySql.Data.MySqlClient.MySqlParameter("#gambar", MySql.Data.MySqlClient.MySqlDbType.LongBlob)).Value = IO.File.ReadAllBytes("man-icon.png") 'Insert field gambar using an existing file in debug folder if file does not exist in PictureBox'
Else
.Parameters.Add(New MySql.Data.MySqlClient.MySqlParameter("#gambar", MySql.Data.MySqlClient.MySqlDbType.LongBlob)).Value = IO.File.ReadAllBytes(opdGambar.FileName) 'Insert field gambar using an existing file in PictureBox'
End If
com.ExecuteNonQuery()
End With
For updating record to database with pictures :
Call konek()
Dim adapter As New MySql.Data.MySqlClient.MySqlDataAdapter("select gambar from tbmahasiswa where ID='" & txtID.Text & "'", conn)
Dim dt As New DataTable("gambar")
adapter.Fill(dt)
strSQL = "update tbmahasiswa set NIM='" & txtNIM.Text & _
"',Nama='" & txtNama.Text & _
"',TglLahir='" & Format(dtpTanggal.Value, "yyyy-MM-dd") & _
"',Alamat='" & txtAlamat.Text & _
"',Jurusan='" & cboJurusan.Text & _
"' ,Gambar=#gambar where id='" & txtID.Text & "'"
com = New MySql.Data.MySqlClient.MySqlCommand(strSQL, conn)
With com
If opdGambar.FileName = Nothing Then
Dim row As DataRow = dt.Rows(0)
Using ms As New IO.MemoryStream(CType(row(0), Byte()))
Dim img As Image = Image.FromStream(ms)
gambar.Image = img
.Parameters.Add(New MySql.Data.MySqlClient.MySqlParameter("#gambar", MySql.Data.MySqlClient.MySqlDbType.LongBlob)).Value = (CType(row(0), Byte())) 'field gambar will use the current existing file in database if PictureBox does not have a file'
End Using
Else
.Parameters.Add(New MySql.Data.MySqlClient.MySqlParameter("#gambar", MySql.Data.MySqlClient.MySqlDbType.LongBlob)).Value = IO.File.ReadAllBytes(opdGambar.FileName)
End If
com.ExecuteNonQuery()
End With
i hope for those who find the other answer a little confusing (like me), will find this answer helpful.
Related
I want to remove the rows of data gridview after use a query sql from database
i use this code
Try
Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("en-US")
Dim strConn As String
strConn = "DRIVER=PostgreSQL ANSI;SERVER=127.0.0.1;PORT=5432;UID=postgres;Password=azerty79;DATABASE=" & ComboBox2.Text & ";pwd=postgres;ReadOnly=0"
'strConn = "DRIVER={PostgreSQL ANSI};UID=postgres;pwd=postgres;LowerCaseIdentifier=0;UseServerSidePrepare=0;ByteaAsLongVarBinary=0;"
'strConn = "dsn=test;uid=postgres;pwd=postgres"
Dim cnDb As OdbcConnection
Dim dsDB As New DataSet
Dim adDb As OdbcDataAdapter
Dim cbDb As OdbcCommandBuilder
Dim cmd As OdbcCommand
Dim cmd1 As OdbcCommand
Dim adDb1 As OdbcDataAdapter
Dim dsDB1 As New DataSet
Dim dt As New DataTable
Dim pic As New PictureBox
cnDb = New OdbcConnection(strConn)
cnDb.Open()
dsDB = New DataSet
adDb = New OdbcDataAdapter
cbDb = New OdbcCommandBuilder(adDb)
'cmd.Parameters.Add("#id", OdbcType.NVarChar, "1")
For i = 1 To 3
' Create the SelectCommand.
cmd = New OdbcCommand("select b.id_detail_polygon,b.mappe_3,b.type_d_affaire,b.consistance,b.nbr_borne ,num_bornes,a.x,a.y,b.superficie_cs from point a right join (select (dp).path[1] d1,(dp).path[2] d2,(dp).geom d3 from (select st_dumppoints(geom) dp from polygon where id_detail_polygon ='" & i & "')a)dptable on st_equals(a.geom,dptable.d3),polygon b where id_detail_polygon='" & i & "'", cnDb) ' & _
'"WHERE id = ? ", cnDb)
cmd1 = New OdbcCommand("SELECT num_bornes,x,y FROM point RIGHT JOIN (SELECT (dp).path[1] As ringID,(dp).path[2] As pointID,(dp).geom ptgeom FROM (SELECT st_dumppoints(geom) dp FROM polygon WHERE id_detail_polygon='" & i & "' ) a) dptable ON ST_Equals(point.geom, dptable.ptgeom) ORDER BY dptable.pointID;", cnDb)
'cmd.Parameters.Add("#id", OdbcType.NVarChar, "1")
adDb = New OdbcDataAdapter(cmd)
adDb1 = New OdbcDataAdapter(cmd1)
adDb.Fill(dsDB, ComboBox1.Text)
adDb1.Fill(dsDB1, ComboBox1.Text)
DataGridView2.DataSource = dsDB
DataGridView3.DataSource = dsDB1
DataGridView2.DataMember = ComboBox1.Text
DataGridView3.DataMember = ComboBox1.Text
DataGridView2.DataSource = dsDB.DefaultViewManager
DataGridView3.DataSource = dsDB1.DefaultViewManager
Dim StrExport As String = ""
For Each R As DataGridViewRow In DataGridView3.Rows
For Each C As DataGridViewCell In R.Cells
If Not C.Value Is Nothing Then
StrExport &= C.Value.ToString & " "
Else
End If
Next
StrExport = StrExport.Substring(0, StrExport.Length - 1)
StrExport &= Environment.NewLine
Next
Dim fName As String = ""
SaveFileDialog1.InitialDirectory = "C:\Users\pc\Desktop\"
SaveFileDialog1.Filter = "dat files (*.dat)|*.dat"
SaveFileDialog1.FilterIndex = 2
SaveFileDialog1.Title = "dat"
SaveFileDialog1.RestoreDirectory = True
If (SaveFileDialog1.ShowDialog() = System.Windows.Forms.DialogResult.OK) Then
fName = SaveFileDialog1.FileName
End If
For j = 0 To 0
For x = 0 To DataGridView2.RowCount - 1
Dim tw As IO.TextWriter = New IO.StreamWriter(fName)
tw.Write(DataGridView2.Rows(j).Cells(0).Value & vbCr & vbLf & DataGridView2.Rows(j).Cells(1).Value & vbCr & vbLf & DataGridView2.Rows(j).Cells(2).Value & vbCr & vbLf & DataGridView2.Rows(j).Cells(3).Value & vbCr & vbLf & DataGridView2.Rows(j).Cells(4).Value & vbCr & vbLf & StrExport & " " & DataGridView2.Rows(j).Cells(8).Value)
tw.Close()
Next
Next
For Each row As DataGridViewRow In DataGridView2.Rows
DataGridView2.Rows.Remove(row)
Next
Next
Catch ex As Exception
MsgBox("ERROR :" + ex.Message)
End Try
MsgBox("Exported", vbInformation, "Successful")
But i get this problem below
Edit
Basing on your comment, I understand you don't want the data gone from the database bug instead from the grid. I would advise against using a dataset as you have done. A DataSet has a collection of DataTable objects that you can manipulate. I also see that you are removing every row in a For Each loop. You can remove these rows from the table or call the clear method on that table and you grid should reflect it. I have left the original answer to explain why this was happening. Edit
Without being able to tell what the error is, I'll just tell you that you cannot programmatically remove a row from a DataGridView if the DataSource is not an IBindingList with change event notification. OdbcDataAdapter does not implement IBindingList anywhere in its inheritance chain.
If you are not willing to change what you bind to, you can re-run the query to get the items and bind the grid again.
I want update mysql database table in vb.net, i try and i got problem with that. this is my source
MysqlConn = New MySqlConnection
MysqlConn.ConnectionString =
"server=db4free.net;port=3306;userid=***;password=***;database=***"
Dim Reader As MySqlDataReader
Try
MysqlConn.Open()
Dim Query As String
Query = "update member set (Name='" & Val(TextBox1.Text) + Val(TextBox6.Text) & "' WHERE Username='" & TextBox8.Text & "'"
Command = New MySqlCommand(Query, MysqlConn)
Reader = Command.ExecuteReader
MysqlConn.Close()
Catch ex As Exception
MsgBox(ex.Message)
Finally
MysqlConn.Dispose()
End Try
If i do this source, i got error code like this
TextBox1.Text = 10
TextBox6.Text = 20
TextBox8.Text = John
Here's what you have
"update member set (Name='" & Val(TextBox1.Text) + Val(TextBox6.Text) & "' WHERE Username='" & TextBox8.Text & "'"
render:
update member set (Name='30' WHERE Username='John'
-
What you probably want is to remove the bracket
"update member set Name='" & Val(TextBox1.Text) + Val(TextBox6.Text) & "' WHERE Username='" & TextBox8.Text & "'"
resulting in :
update member set Name='30' WHERE Username='John'
My suggestion to you as a preference for building these strings is to separate the parameters more often. It keeps things neat and easy.
ex:
dim x as string = (Val(TextBox1.Text) + Val(TextBox6.Text)).tostring
dim cmd as string =
"update member " &
"set Name=" & "'" & x & "' " &
"WHERE Username=" & "'" & TextBox8.Text & "'"
Im a newbie in VB2010 & in MYSQL Database.
I have 2 database one on MS SQL 2008 (BigData) and another on Mysql. I have written some code in VB2010 to fetch data from SQL2008 and insert into MySQL. My goal is to transfer all data from MS SQL to MySQL as quick as I can thats why I created a simple vb script that will act as middleware to transfer data from MS SQL to MySQL.
My Headache is, almost 1 hour to transfer the 28,000 records from MS SQL to MySQL database. Is there any easiest way to transfer the data or I need to enhance my VBScript program. Please help to improve my VBScript below.
Thank you in advance.
Imports MySql.Data.MySqlClient
Imports System.Data
Imports System.Data.SqlClient
Public Class Form1
Dim SQLConnectionSQL As MySqlConnection = New MySqlConnection
Dim connectionStringSQL As String = "Data Source=solomon;Initial Catalog=testapp;Persist Security Info=True;User ID=sa;Password=Passw0rd"
Dim connectionString As String = "Server=192.168.1.199; User Id=gil; Password=Passw0rd; Database=testapp"
Dim SQLConnection As MySqlConnection = New MySqlConnection
Dim oDt_sched As New DataTable()
Private Sub btnRetrieve_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnRetrieve.Click
Dim con_Solomon As String
Dim connection As SqlConnection
Dim command As SqlCommand
Dim adapter As New SqlDataAdapter
Dim ds As New DataSet
Dim sql As String
Dim str_carSql As String
lblCounter.Text = 0
con_Solomon = "Data Source=solomon;Initial Catalog=MARYLANDAPP;Persist Security Info=True;User ID=sa;Password=Passw0rd"
sql = "SELECT LTRIM(RTRIM(DocType)) as DocType, LTRIM(RTRIM(cust_classID)) as cust_classID, LTRIM(RTRIM(salesman)) as salesman, LTRIM(RTRIM(CustId)) as CustId, LTRIM(RTRIM(name)) as name, LTRIM(RTRIM(ClassID)) as ClassID, LTRIM(RTRIM(invoice_no)) AS refnbr, invoice_delv_date AS Delv_DocDate, Age, AR_Amount, LTRIM(RTRIM(STATUS)) as STATUS, LTRIM(RTRIM(AGE_GROUP)) as AGE_GROUP, LTRIM(RTRIM(company)) AS comp, '' AS Deposit_Date, Credit_Limit, LTRIM(RTRIM(Terms)) as Terms, LTRIM(RTRIM(customer_name)) AS ShipName, LTRIM(RTRIM(PO_Number)) as PO_Number, LTRIM(RTRIM(Kob)) as Kob, LTRIM(RTRIM(check_date)) as check_date FROM a_aging_ardoc_report"
connection = New SqlConnection(con_Solomon)
Try
connection.Open()
command = New SqlCommand(sql, connection)
command.CommandTimeout = 420
adapter.SelectCommand = command
adapter.Fill(ds, "PO_Monitoring")
adapter.Dispose()
command.Dispose()
connection.Close()
''****** MYSQL CONNECTION *****
SQLConnection = New MySqlConnection()
SQLConnection.ConnectionString = connectionString
SQLConnection.Open()
Dim sqlCommand As New MySqlCommand
Dim delv_docdate, check_date
For a = 0 To ds.Tables(0).Rows.Count - 1
With ds.Tables(0).Rows(a)
If Not IsDBNull(.Item(7)) Then
delv_docdate = .Item(7)
Else
delv_docdate = ""
End If
If Not IsDBNull(.Item(19)) Then
check_date = .Item(19)
Else
check_date = ""
End If
str_carSql = "insert into agingreportsummary(doctype,cust_classid,salesman,custId,name,classid,refnbr,delv_docdate,age,ar_amount,status,age_group,comp,credit_limit,terms,shipname,po_number,kob,check_date) " & _
"VALUES('" & .Item(0) & "','" & .Item(1) & "','" & Replace(.Item(2), "'", "") & "','" & .Item(3) & "','" & Replace(.Item(4), "'", "") & "','" & Replace(.Item(5), "'", "") & "','" & .Item(6) & "','" & delv_docdate & "'," & Replace(.Item(8), ",", "") & "," & Replace(.Item(9), ",", "") & ",'" & Replace(.Item(10), "'", "") & "','" & .Item(11) & "','" & .Item(12) & "','" & .Item(14) & "','" & .Item(15) & "','" & Replace(.Item(16), "'", "") & "','" & Replace(.Item(17), "'", "") & "','" & .Item(18) & "','" & check_date & "');"
End With
sqlCommand.Connection = SQLConnection
sqlCommand.CommandText = str_carSql
sqlCommand.ExecuteNonQuery()
Next a
SQLConnection.Close()
MsgBox("Finish")
Catch ex As Exception
MsgBox(str_carSql)
MsgBox(ex.Message)
End Try
End Sub
End Class
You can try using a parameterised query instead of building a query for each row. That should improve things slightly since the statement wouldn't need to be prepared every time.
Add all the required parameters to the command.
Set the command text once, and change it to use parameters.
Inside the loop you would only set the parameter values and call the executenonquery method
This would have the added benefit of not being vulnerable to sql injection.
Hope that helps
Hoping someone can help me out with this.
I've made an app linked to a mysql db.
I'm writing details of remote hosts to a database at the minute.
I'm saving remote credentials too, but in a different table.
I have a colomn in my 'credentials' table called 'hosts_linked_id' which i want to contain the id of the parent record in the 'hosts' table.
Here is my code so far...
SQLConnection.ConnectionString = connectionstring
Try
If SQLConnection.State = ConnectionState.Closed Then
SQLConnection.Open()
Dim SQLStatement As String = "INSERT INTO hosts(name, description, host, type, port) VALUES('" & txtname.Text & "','" & txtdescription.Text & "','" & txthost.Text & "','" & cmbtype.Text & "','" & txtport.Text & "')"
SaveData(SQLStatement)
SQLConnection.Open()
SQLStatement = "INSERT INTO credentials(hosts_linked_id, username, password, type) VALUES('" & txtname.Text & "','" & txtusername.Text & "','" & encryptedpassword & "','" & cmbtype.Text & "')"
SaveData(SQLStatement)
Else
SQLConnection.Close()
End If
Also, here's the 'SaveData' function...
Public Sub SaveData(ByRef SQLStatement As String)
Dim cmd As MySqlCommand = New MySqlCommand
With cmd
.CommandText = SQLStatement
.CommandType = CommandType.Text
.Connection = SQLConnection
.ExecuteNonQuery()
End With
SQLConnection.Close()
MsgBox("Host has been added")
txtname.Text = ""
txtdescription.Text = ""
txthost.Text = ""
cmbtype.Text = ""
txtport.Text = ""
End Sub
What i need to do is get the id of the record created when my first 'INSERT' statement is executed into a variable so i can insert it into the 'credentials' table when my second 'INSERT' statement is executed.
I've googled the hell out of this and tried a few different methods, all without success.
Can anyone help point me in the right direction?
Thanks in advance!!
TL;DR: Need to get the ID of mysql record added when insert statement is executed and drop it into a variable
When I run this function
For RepeatBooking = 1 To 51
dateConvertedDateToBook = dateDateToBook.Date
dateDateToBook = dateDateToBook.AddDays(7)
strDateToBook = dateConvertedDateToBook.ToString("yyyy-MM-dd")
Try
Dim command As MySqlCommand = New MySqlCommand
Dim sqlQuery As String = "INSERT INTO bookings SET Date=" & "'" & strDateToBook & "',RoomID='" & strComputerRoomToBook & "',Length='" & intNewBookingLength & "',Period='" & intNewStartPeriod & "',UserID='" & intid & "'"
Dim reader As MySqlDataReader
SQLConnection.Open()
command.CommandText = sqlQuery
command.Connection = SQLConnection
reader = command.ExecuteReader
SQLConnection.Close()
Catch excep As Exception
MsgBox(excep.ToString)
End Try
Next
in my program I get an error saying "The connection property has not been set or is null"
How can I get rid of this?
It goes to the exception when it gets to SQLconnection.Open()
I created the ServerString and MySQL connection at the top of the module like so:
Dim ServerString As String = "Server=localhost;User Id=root;Password=**********;Database=rooms"
Dim SQLConnection As MySqlConnection = New MySqlConnection
You are opening a connection without its property
It should be,
Dim SQLConnection As New MySqlConnection(ServerString)
SQLConnection.Open
Also, you may want to use the USING function so that your connection is properly closed.
It seems you are just inserting a bunch of values to your database and not retrieving anything so why do you use a DataReader?
Your code should be something like this:
Using SQLConnection = New MySqlConnection(ServerString)
SQLConnection.Open 'You should open a connection only once
For RepeatBooking = 1 To 51
dateConvertedDateToBook = dateDateToBook.Date
dateDateToBook = dateDateToBook.AddDays(7)
strDateToBook = dateConvertedDateToBook.ToString("yyyy-MM-dd")
Try
Dim sqlQuery As String = "INSERT INTO bookings SET " & _
"Date='" & strDateToBook & "'," & _
"RoomID='" & strComputerRoomToBook & "', " & _
"Length='" & intNewBookingLength & "', " & _
"Period='" & intNewStartPeriod & "', " & _
"UserID='" & intid & "'"
Dim command = New MySqlCommand(sqlQuery, SQLConnection)
command.ExecuteNonQuery
Catch excep As Exception
MsgBox(excep.Message)
End Try
Next
End Using
Also, you may want to change how to pass your values into a parameter. This will prevent SQL Injection.