sqlite read pdf file from database - vb.net

I'm a little stuck with this...
I have a code to insert a PDF file into a blob as bytes:
Dim ofd As New OpenFileDialog
With ofd
.InitialDirectory = Application.StartupPath
.Filter = "PDF Files|*.pdf"
.FileName = Nothing
.ShowDialog()
End With
MsgBox(ofd.FileName)
Dim filePath As String = ofd.FileName
Dim filename As String = Path.GetFileName(filePath)
Dim fs As FileStream = New FileStream(filePath, FileMode.Open, FileAccess.Read)
Dim br As BinaryReader = New BinaryReader(fs)
Dim bytes As Byte() = br.ReadBytes(Convert.ToInt32(fs.Length))
br.Close()
fs.Close()
Dim con As New SQLiteConnection(db)
Dim cmd As New SQLiteCommand
Try
con.Open()
cmd = con.CreateCommand
cmd.CommandText = "UPDATE Employee SET File = #File WHERE ID = 20"
cmd.Parameters.Add("#File", SqlDbType.Binary).Value = bytes
cmd.ExecuteNonQuery()
Catch ex As Exception
MsgBox(ex.Message)
Finally
con.Close()
cmd.Dispose()
End Try
This works, but now I need to reverse it and load the PDF file (I don't want to save the PDF back into the computer, all I need is to view it...)
This is what I have to retrieve the PDF file:
Dim con As New SQLiteConnection(db)
Dim cmd As New SQLiteCommand
Dim File As New DataTable
Try
con.Open()
cmd = con.CreateCommand
Dim CommandText As String = "SELECT File FROM Employee WHERE ID = 20"
Dim adapter As New SQLiteDataAdapter(CommandText, con)
adapter.Fill(File)
Catch ex As Exception
MsgBox(ex.Message)
Finally
con.Close()
cmd.Dispose()
End Try
But it doesn't work...
Anyone have another way to do it?

So this is how I fixed it...
Try
con.Open()
cmd = con.CreateCommand
cmd.CommandText = "SELECT File FROM Employee WHERE ID = 20"
Dim bytes As Byte() = cmd.ExecuteScalar()
Dim fs As FileStream = New FileStream("d:\test.pdf", FileMode.Create)
fs.Write(bytes, 0, bytes.Length)
fs.Close()
Catch ex As Exception
MsgBox(ex.Message)
Finally
con.Close()
cmd.Dispose()
End Try
Thanks for the help

Related

How to add Header Columns to PDF Sql, Vb.net

How to add Header Columns('ID, Name, Class, Date'. When I'm exporting to pdf from database pdf documnet not showing header columns how to add header columns to pdf. Thank you...
Dim table As New PdfPTable(5)
table.TotalWidth = 516.0F
table.LockedWidth = False
Dim widths As Single() = New Single() {1.0F, 2.0F, 3.0F, 4.0F, 5.0F}
table.SetWidths(widths)
table.HorizontalAlignment = 0
table.SpacingBefore = 20.0F
table.SpacingAfter = 20.0F
Dim connect As String = "Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\nagaraju\Documents\Attendance.mdf;Integrated Security=True;Connect Timeout=30"
Using conn As New SqlConnection(connect)
Dim pdfDoc As New Document()
Dim pdfWrite As PdfWriter = PdfWriter.GetInstance(pdfDoc, New FileStream("C:\Users\nagaraju\Documents\pdf\" & TextBox1.Text & ".pdf", FileMode.Create))
pdfDoc.Open()
Dim img As Image = Image.GetInstance(My.Resources.Header, System.Drawing.Imaging.ImageFormat.Jpeg)
pdfDoc.Add(img)
img.ScalePercent(50.0F)
img.ScaleToFit(250.0F, 250.0F)
Dim query As String = "SELECT ID,Name,Class,Date,Intime FROM stuattrecordAMPM where ID=#ID and Date between #Date1-1 and #Date2"
Dim cmd As New SqlCommand(query, conn)
cmd.Parameters.Add("#ID", SqlDbType.Int)
cmd.Parameters("#ID").Value = TextBox1.Text
cmd.Parameters.Add("#Date1", SqlDbType.DateTime).Value = DateTimePicker1.Value
cmd.Parameters.Add("#Date2", SqlDbType.DateTime).Value = DateTimePicker2.Value
Try
conn.Open()
Using rdr As SqlDataReader = cmd.ExecuteReader()
While rdr.Read()
table.AddCell(rdr(0).ToString())
table.AddCell(rdr(1).ToString())
table.AddCell(rdr(2).ToString())
table.AddCell(rdr(3).ToString())
table.AddCell(rdr(4).ToString())
End While
End Using
Catch ex As Exception
End Try
pdfDoc.Add(table)
pdfDoc.Close()
End Using

Why is my VB program throwing an exception complaining that a OleDbDataReader is closed, when it should absolutely be open?

I am trying to use OleDB and SQLBulkCopy to pull data off an excel spreadsheet, into an SQL database. When I try and run my code, I get the following exception, triggered by
"bulkCopy.WriteToServer(objDR)" (which is also described in the question title): exception data
OleDB successfully reads the excel sheet which is then populated properly in the DataGridView I created within a WinForm for debugging purposes.
Below is a snippet of the relevant code.
Dim ExcelConnection As New System.Data.OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=\\damon\Everyone\sheet1erictest.xlsx;Extended Properties=""Excel 12.0 Xml;HDR=Yes""")
ExcelConnection.Open()
Dim sheet As String = "Sheet5$"
Dim expr As String = "SELECT * FROM [" + sheet + "]"
Dim objCmdSelect As OleDbCommand = New OleDbCommand(expr, ExcelConnection)
Dim objDR As OleDbDataReader
Dim SQLconn As New SqlConnection()
Dim ConnString As String = "SERVER=SqlDEV;DATABASE=Freight;Integrated Security=True"
SQLconn.ConnectionString = ConnString
SQLconn.Open()
Using bulkCopy As SqlBulkCopy = New SqlBulkCopy(SQLconn)
bulkCopy.DestinationTableName = "dbo.test"
Try
objDR = objCmdSelect.ExecuteReader
Dim dt = New DataTable()
dt.Load(objDR)
DataGridView1.AutoGenerateColumns = True
DataGridView1.DataSource = dt
DataGridView1.Refresh()
bulkCopy.WriteToServer(objDR)
objDR.Close()
SQLconn.Close()
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Using
End Sub
Your reader object is being used by the DataTable, so comment out those lines and run them separately later with a new instance:
objDR = objCmdSelect.ExecuteReader
'Dim dt = New DataTable()
'dt.Load(objDR)
'DataGridView1.AutoGenerateColumns = True
'DataGridView1.DataSource = dt
'DataGridView1.Refresh()
bulkCopy.WriteToServer(objDR)

A generic error occurred in GDI+ when update

When I update a form I have this error only when I don't update(change) the image.
When I update with a new image I don't have this error.
Try
Dim mstream As New System.IO.MemoryStream()
PictureBox1.Image = New Bitmap(Image.FromStream(mstream))
Dim arrImage() As Byte = mstream.GetBuffer()
mstream.Close()
MysqlConn.Close()
MysqlConn.Open()
COMMAND.Connection = MysqlConn
COMMAND.CommandText = "update product set
id_maker=#Value1,
foto=#foto
where id = '" & TextBox1.Text & "'"
COMMAND.Parameters.AddWithValue("#Value1", If(String.IsNullOrEmpty(ComboBox1.Text), DBNull.Value, ComboBox1.Text))
COMMAND.Parameters.AddWithValue("#foto", arrImage)
READER = COMMAND.ExecuteReader
MessageBox.Show("Datos Guardados")
MysqlConn.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
Finally
MysqlConn.Dispose()
End Try
MysqlConn.Close()
I Try this and work.
Dim mstream As New System.IO.MemoryStream()
'PictureBox1.Image = New Bitmap(Image.FromStream(mstream))
PictureBox1.Image.Save(mstream, System.Drawing.Imaging.ImageFormat.Jpeg)
Dim arrImage() As Byte = mstream.GetBuffer()

odbc reader for csv in vb.net

I'm writing a program that should handle million of datasets in csv in a short time, my idea was to use odbc because of performance reasons, therefore i read all the data with odbc and save it in memory, thereafter i add parameters and insert it in sql db, here is my code so far:
Using connection As New OdbcConnection("jdbc:odbc:Driver={Microsoft Text Driver (*.txt; *.csv)};" & filePath & "Extensions=csv;Persist Security Info=False;")
Dim reader As OdbcDataReader
Dim i As Integer
Dim r As SeekZeilen
Dim TextFileTable As DataTable = Nothing
Dim line As String = reader.Read()
Me.ParseString(line)
Dim memStream As New MemoryStream(Encoding.Default.GetBytes(line))
Using TextFileReader As New Microsoft.VisualBasic.FileIO.TextFieldParser(memStream)
TextFileReader.TextFieldType = FileIO.FieldType.Delimited
TextFileReader.SetDelimiters(";")
r.erste_Zeile = TextFileReader.ReadFields()
If TextFileTable Is Nothing Then
TextFileTable = New DataTable("TextFileTable")
For i = 0 To r.erste_Zeile.Length - 1
Dim Column As New DataColumn(r.erste_Zeile(i))
Column.ReadOnly = True
TextFileTable.Columns.Add(Column)
Next
End If
DataGridView1.DataSource = TextFileTable
End Using
While reader.HasRows
line = reader.Read()
Me.ParseString(line)
memStream = New MemoryStream(Encoding.Default.GetBytes(line))
Using TextFileReader As New Microsoft.VisualBasic.FileIO.TextFieldParser(memStream)
TextFileReader.TextFieldType = FileIO.FieldType.Delimited
TextFileReader.SetDelimiters(";")
DataGridView1.DataSource = TextFileTable
Try
r._Rest = TextFileReader.ReadFields()
ReplaceChars(r._Rest)
If Not r._Rest Is Nothing Then
Dim oSQL As New DBUmgebung.cdb.SQL()
oSQL.init()
AddParameters(oSQL, r)
oSQL.ausfuehrenSQL(DBUmgebung.cdb.KSQLCommand.INSERT, _table, "")
Dim dtRow As DataRow = TextFileTable.NewRow
For i = 0 To r._Rest.Length - 1
dtRow(i) = r._Rest(i).ToString()
Next
TextFileTable.Rows.Add(dtRow)
DataGridView1.Refresh()
Application.DoEvents()
End If
Catch ex As Microsoft.VisualBasic.FileIO.MalformedLineException
MsgBox("Error! " & ex.Message & _
"")
Catch sqlEx As SqlException
MessageBox.Show(sqlEx.Message)
rtbSql.Focus()
Exit For
Catch ex As Exception
MessageBox.Show(ex.Message)
rtbSql.Focus()
Exit For
End Try
End Using
End While
reader.Close()
End Using
the problem is that i get null pointer exception for a unknown reason, does anyone have idea what i did wrong? is it probably because my odbc reader is not properly initialized?
Try this. This will read the csv file as all text into a datatable. Once in the Datatable you could then insert the records into SQL. You can always adjust this to handle multiple csv files.
Friend Shared Function GetExcelFile(ByVal strFileName As String, ByVal strPath As String) As DataTable
Try
Dim dt As New DataTable
Dim ConStr As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & strPath & ";Extended Properties=""Text;HDR=Yes;FMT=Delimited\"""
Dim conn As New OleDb.OleDbConnection(ConStr)
Dim da As New OleDb.OleDbDataAdapter("Select * from " & strFileName, conn)
da.Fill(dt)
Return dt
Catch ex As Exception
Return Nothing
End Try
End Function

Trouble in displaying an image to datagridview

I'm having a trouble in viewing or displaying an image from the database (mysql) to datagriview
The table in my database that I'm trying to retrieve is named as sample with fields ID = Int(10), primary, auto increment and IMG = blob
Anyone who can help me with this? It will be so much appreciated
Sub getData()
Try
Dim Sql = "Select ID, IMG from sample"
connectionOn()
Dim cmd = New MySqlCommand(Sql, ConOn)
Dim dr = cmd.ExecuteReader(CommandBehavior.CloseConnection)
DataGridView1.Rows.Clear()
While dr.Read = True
Dim mybytearray As Byte() = dr.Item("IMG")
Dim myimage As Image
Dim ms As System.IO.MemoryStream = New System.IO.MemoryStream(mybytearray)
myimage = System.Drawing.Image.FromStream(ms)
DataGridView1.Rows.Add(dr(0), myimage)
End While
ConOn.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Below is my code saving the image in the database. But it doesn't save anything. I want to get the image from the datagrid then save it to the database
Try
connectionSync()
Dim a, b As String
Dim Sql = "INSERT INTO SAMPLE (ID, IMG)values(#a,#b)"
For i As Integer = 0 To Me.DataGridView1.Rows.Count - 1
a = Me.DataGridView1.Rows(i).Cells(0).Value.ToString()
Dim cmd As New MySqlCommand(Sql, ConSync)
Dim memorystream1 As New MemoryStream()
Dim filename As String = DataGridView1.Rows(i).Cells(1).Value
Dim bitmaps As New Bitmap(filename)
bitmaps.Save(memorystream1, Imaging.ImageFormat.Jpeg)
Dim pic() As Byte = memorystream1.GetBuffer()
cmd.Parameters.AddWithValue("#a", a)
cmd.Parameters.AddWithValue("#b", bitmaps)
cmd.ExecuteNonQuery()
cmd.Parameters.Clear()
Next
ConSync.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
Since MySql BLOB Type is used to stored SqlServer IMAGE Type I think you can adapt this code using MySql classes (i.e.: MySqlDataAdapter instead of SqlDataAdapter):
Try
Me.DataGridView1.DataSource = Nothing
Dim dgvID As New DataGridViewTextBoxColumn
dgvID.DataPropertyName = "ID"
Dim dgvIMG As New DataGridViewImageColumn
dgvIMG.DataPropertyName = "IMG"
Me.DataGridView1.Columns.Add(dgvID)
Me.DataGridView1.Columns.Add(dgvIMG)
connectionOn()
Dim cmdSample As SqlCommand = ConOn.CreateCommand
cmdSample.CommandText = "SELECT ID, " _
& "IMG " _
& "FROM Sample"
Dim dtSample As New DataTable
Dim daSample As New SqlDataAdapter(cmdSample)
daSample.Fill(dtSample)
Me.DataGridView1.DataSource = dtSample
ConOn.Close()
ConOn.Dispose()
Catch ex As Exception
MsgBox(ex.Message)
End Try