I have an ASP .NET Web Form application to upload files to a MySql 5.5 table.
When I click the submit button the query is executed but in the table only the Identity column gets a value.
The columns for the file attributes i.e FileName(varchar (50)) , ContentType(varchar (50))
and Content (medium blob) are blank. All other controls e.g textboxes execute insert operations from the application except the Asp:FileUpload control.
My code is as below:
Protected Sub UploadFile()
Dim filename As String = Path.GetFileName(fuCollateral.PostedFile.FileName)
Dim contentType As String = fuCollateral.PostedFile.ContentType
Dim iFileLen As Integer
Dim byteFileData As Byte()
Dim uploadedFile As HttpPostedFile = fuCollateral.PostedFile
If fuCollateral.HasFile Then
uploadedFile = fuCollateral.PostedFile
iFileLen = uploadedFile.ContentLength
ReDim byteFileData(iFileLen)
uploadedFile.InputStream.Read(byteFileData, 0, iFileLen)
Using fs As Stream = fuCollateral.PostedFile.InputStream
Using br As New BinaryReader(fs)
Dim bytes As Byte() = br.ReadBytes(DirectCast(fs.Length, Long))
Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
Using con As New MySqlConnection(constr)
Dim query As String = "INSERT INTO imagefiles(FileName, ContentType, Content) VALUES (#FileName, #ContentType, #Content)"
Using cmd As New MySqlCommand(query)
cmd.Connection = con
cmd.Parameters.Add(New MySqlParameter("#FileName", filename))
cmd.Parameters.Add(New MySqlParameter("#ContentType", contentType))
cmd.Parameters.Add(New MySqlParameter("#Content", bytes))
con.Open()
cmd.ExecuteNonQuery()
con.Close()
End Using
End Using
End Using
End Using
End If
End Sub
The code of the button click event:
Protected Sub btnSubmit_Click(sender As Object, e As EventArgs) Handles btnSubmit.Click
UploadFile()
End Sub
Screenshot of table after clicking submit:
enter image description here
Related
i created a simple mass upload of data from CSV to datagridview and save all datagridview rows into my MySQL table, the code works perfectly but when i check my database it insert a null values to my table heres my code.
This is my Button for Adding all values from my Datagridview
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim cmd As MySqlCommand
connection.Open()
Dim i As Integer
For i = 0 To DataGridView1.Rows.Count - 2
Dim row As DataGridViewRow = DataGridView1.Rows(i)
cmd = New MySqlCommand("INSERT INTO tbl_handling(tbl_docnumber,tbl_bpref,tbl_cname) values (#docnumber,#bref,#cname)", connection)
cmd.Parameters.Add("#docnumber", MySqlDbType.Int64).Value = DataGridView1.Rows(i).Cells(0).Value.ToString
cmd.Parameters.Add("#bref", MySqlDbType.VarChar).Value = DataGridView1.Rows(i).Cells(1).Value.ToString
cmd.Parameters.Add("#cname", MySqlDbType.VarChar).Value = DataGridView1.Rows(i).Cells(2).Value.ToString
cmd.ExecuteNonQuery()
Next
connection.Close()
connection.Dispose()
MessageBox.Show("Data All Uploaded")
End Sub
This is my code on inserting CSV file to my Datagrid view
Private Sub btnUpload_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSelectData.Click
Dim fName As String = ""
OpenFileDialog1.InitialDirectory = "D:\TestFile"
OpenFileDialog1.Filter = "CSV files(*.csv)|*.csv"
OpenFileDialog1.RestoreDirectory = True
Dim colespected As Integer = 5
Dim sline As String = ""
If (OpenFileDialog1.ShowDialog() = Windows.Forms.DialogResult.OK) Then
fName = OpenFileDialog1.FileName
Dim thereader As New StreamReader(fName, Encoding.Default)
Do
sline = thereader.ReadLine
If sline Is Nothing Then Exit Do
Dim words() As String = sline.Split(",")
DataGridView1.Rows.Add("")
For ix As Integer = 0 To 2
DataGridView1.Rows(DataGridView1.Rows.Count - 1).Cells(ix).Value = words(ix)
Next
Loop
thereader.Close()
End If
End Sub
I am assuming that your data is displaying successfully in the grid. So I am only addressing the Button event.
Both commands and connections need to be closed and disposed. Using...End Using blocks do this for you. (BTW Stream objects should be in Using blocks also.) Database objects should be local to the method where they are used. If you .Dispose a connection how do you expect to .Open it later? The command and parameters collection are only created once outside the loop. Just the .Value changes inside the loop.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Using connection As New MySqlConnection(ConStr),
cmd As New MySqlCommand("INSERT INTO tbl_handling(tbl_docnumber,tbl_bpref,tbl_cname) values (#docnumber,#bref,#cname)", connection)
cmd.Parameters.Add("#docnumber", MySqlDbType.Int64)
cmd.Parameters.Add("#bref", MySqlDbType.VarChar)
cmd.Parameters.Add("#cname", MySqlDbType.VarChar)
connection.Open()
For i = 0 To DataGridView1.Rows.Count - 2
cmd.Parameters("#docnumber").Value = CLng(DataGridView1.Rows(i).Cells(0).Value)
cmd.Parameters("#bref").Value = DataGridView1.Rows(i).Cells(1).Value.ToString
cmd.Parameters("#cname").Value = DataGridView1.Rows(i).Cells(2).Value.ToString
cmd.ExecuteNonQuery()
Next
End Using
MessageBox.Show("Data All Uploaded")
End Sub
I am a bit worried that tbl_docnumber is an auto-number (identity) primary key in the database. If this is so, then this field should be omitted from the Insert.
This operation would be easier if you filled a DataTable instead of a DataGridView. You could then use a DataAdapter to update the database.
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 was following a tutorial on the internet ( link ) to create a a picture gallery. I got it all working, but i changed:
Private Sub CreateGallery()
i = 0
RemoveControls()
If Directorypath IsNot Nothing Then
Dim di As New IO.DirectoryInfo(Directorypath)
Dim diar1 As IO.FileInfo() = di.GetFiles("*.jpg").Concat(di.GetFiles("*.bmp")).Concat(di.GetFiles("*.png")).Concat(di.GetFiles("*.gif")).ToArray
Dim dra As IO.FileInfo
For Each dra In diar1
DrawPictureBox(dra.FullName, dra.Name)
Next
End If
End Sub
to:
Private Sub CreateGallery()
Dim table = New DataTable
Using Connection = New MySqlConnection("Server=localhost;User Id=root;Password=barra;Database=pap")
Using da = New MySqlDataAdapter("SELECT * FROM filme", Connection)
da.Fill(table)
End Using
End Using
i = 0
RemoveControls()
For Each row As DataRow In table.Rows
Try
Dim bytes() As Byte
bytes = (row("imagem"))
Dim memStream As New MemoryStream(bytes)
DrawPictureBox(memStream, row("titulo"))
Catch ex As Exception
End Try
Next
End Sub
It was working fine, the way i wanted, when i tried to do it on another project it gives me an error on 'MySqlDataAdapter':
Using da = New MySqlDataAdapter("SELECT * FROM filme", Connection)
the erros says : Overload resolution failed because no accessible 'New' can be called with these arguments
I tried almost everything i can't make it work.
convert your function as class and call :
dim new_creator as yourclass
...
Try This
Private Sub CreateGallery()
Dim table As New DataTable
Dim Conn As New SqlConnection
Conn = New SqlConnection("Initial Catalog=<DataBase>;User ID=sa;password=<password>;Data Source=<ServerName>"")
Dim com As String = ""
com = "SELECT * FROM Table "
Dim getComm As New SqlDataAdapter(com, Conn)
getComm.Fill(table)
i = 0
RemoveControls()
For Each row As DataRow In table.Rows
Dim bytes() As Byte
bytes = (row("Imagee"))
Dim memStream As New MemoryStream(bytes)
DrawPictureBox(memStream, row("Bro_Path"))
End Sub
and change ByVal _filename As MemoryStream,
Private Sub DrawPictureBox(ByVal _filename As MemoryStream, ByVal _displayname As String)
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
I have 2 forms, in the first form the datagrid populates with data in mysql. Then to repeat this for my second form I copied the code over and changed all variable names, but when I load the form the datagrid is not populated with mysql data, it doesn't even throw an error. Here is the code I used for my first form and below is for my second form.
This is the code for the second form, where it doesn't work, the code is exactly the same (changed variable names) for the first form.
Second form:
Public Class frmShareholderDetails
Dim connection As New MySqlConnection
Dim myadapter As New MySqlDataAdapter
Dim mycommandbuilder As MySqlCommandBuilder
Dim mycommand As MySqlCommand
Dim datatable As New DataTable
Dim dataset As New DataSet
Dim mydatagridviewprinter As datagridviewprinter
Dim objconnection As New MySqlConnection("Server=localhost;database=ba-solutions;user id=root;password=")
'declaring variables
Private Sub frmShareholderDetails_Load(ByVal sender As System.Object, ByVal e As System.EventArgs)
connection.ConnectionString =
("Server=localhost;database=ba-solutions;user id=root;password=")
Try
connection.Open()
'opens connection
Catch ex As Exception
MsgBox("Cannot connect to BA-Solutions Database")
End Try
myadapter.SelectCommand = New MySqlCommand
myadapter.SelectCommand.Connection = connection
myadapter.SelectCommand.CommandText = "select * from Shareholder_Details"
'creates adapters
mycommandbuilder = New MySqlCommandBuilder(myadapter)
myadapter.Fill(datatable)
myadapter.SelectCommand.CommandType = CommandType.Text
dataset = New DataSet
myadapter.Fill(dataset, "Shareholder_Details")
rowposition = 0
DGVShareholder.DataSource = dataset.Tables("Shareholder_Details")
'sets datasource
connection.Close()
'close connection
Dim recordsondisplay As Integer
recordsondisplay = DGVShareholder.RowCount
lblRecords.Text = recordsondisplay & " records in database."
End Sub
End Class
Can anyone see where the problem lies? I have been using trial and error, but no solution yet.