How to insert data from XML in MySql? - mysql

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

Related

How to fix an empty .csv file export from vb.net using MySQL?

im trying to export a data table to a .csv file in vb.net Ive written code that opens a save file dialogue and successfully saves the .csv file but the file is 0 bytes and contains no data. I'm using MySQL database, the database name is "tickedoff" and the table that i want to export is "pet".
If anyone can see a mistake in my code and help me it would be greatly appreciated.. I am totally stumped at the moment.
This code is in Form1 (button click event):
Private Sub btnPetInfoExport_Click(sender As Object, e As EventArgs) Handles btnPetInfoExport.Click
Dim saveFileDialog1 = New SaveFileDialog()
Dim statement As String = "SELECT pet.petID, pet.petName, pet.species, pet.breed, " _
& "pet.DOB, pet.gender, pet.weight," _
& "CONCAT(customer.lastName, ', ', customer.firstName) AS Customer " _
& "FROM pet INNER JOIN customer ON pet.customerID = customer.customerID " _
& "ORDER BY pet.petID"
Dim petDataTable As DataTable =
DataAccessLayer.GetPetDataTableForExport(statement)
Dim saveFile As StreamWriter
Dim fileName As String = String.Empty
Dim csvBuilder As New StringBuilder()
For i = 0 To petDataTable.Columns.Count - 1
csvBuilder.Append(petDataTable.Columns(i).ColumnName + ","c)
Next
csvBuilder.Append(vbCr & vbLf)
For i = 0 To petDataTable.Rows.Count - 1
For o = 0 To petDataTable.Columns.Count - 1
csvBuilder.Append(petDataTable.Rows(i)(o).ToString().Replace(",", ";") + ","c)
Next
csvBuilder.Append(vbCr & vbLf)
Next
saveFileDialog1.Filter = "CSV files ( .csv)|.csv|ALL files (.)|. "
If saveFileDialog1.ShowDialog = System.Windows.Forms.DialogResult.OK Then
fileName = saveFileDialog1.FileName
Try
saveFile = File.CreateText(fileName)
Catch ex As Exception
Throw ex
End Try
End If
End Sub
This function is called from the above sub and is in a separate class called "data access layer":
Public Shared Function GetPetDataTableForExport(statement As String) As
DataTable
Dim petDataTableCommand As New MySqlCommand(statement)
Dim petDataTable As New DataTable()
Dim connection As New MySqlConnection("server=localhost; Port=3306; database=tickedoff; username=root;")
Dim petDataTableAdapter As MySqlDataAdapter = New MySqlDataAdapter
petDataTableCommand.CommandType = CommandType.Text
petDataTableCommand.Connection = connection
Try
connection.Open()
petDataTableAdapter.SelectCommand = petDataTableCommand
'fill the table with the pet data from the database
petDataTableAdapter.Fill(petDataTable)
Catch ex As Exception
Throw ex
Finally
connection.Close()
petDataTableAdapter.Dispose()
connection.Dispose()
End Try
Return petDataTable
End Function

Display saved PDF file from database to PDFVIEWER

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.

vb 2010 mysql insert record operation inserts a blank record but no data is inserted

I am trying to develop a utility in vb 2010, which will store values from Datagridview control to a mysql table
Steps
1) Datagrid cell values are stored in an array
2) Array values are used .AddWithValue() function
Present status: Only a blank record is inserted. Data is missing.
Please refer to following code.
Function insertRec()
'dgExistingProject is datagridview control embedded on the form
Dim ServerString As String = "Server=pnserver;User ID=root;
Password=; Database=prayer_net"
Dim Arr(RCount) As String
Dim SQLConn As MySqlConnection = New MySqlConnection
SQLConn.ConnectionString = ServerString
dim I as Integer
For I = 0 To RCount
Arr(I) = dgExistingProject.Rows(I).Cells(1).Value
Next
Try
Dim dt As Date = DateTime.Now.ToString("yyyy/MM/dd
HH:mm:ss")
Dim projName as Integer=Arr(4)
Using sqlCommand As New MySqlCommand
With sqlCommand
.CommandText = "INSERT INTO dyn_dwg_register
(file_name,file_location,dwg_description,
project_id,created_by, created_on)" & _
" values (#file_name, #file_location, #dwg_description, #project_id, #created_by, #created_on)"
.CommandType = CommandType.Text
.Connection = SQLConn
.Parameters.AddWithValue("#file_name", Arr(0))
.Parameters.AddWithValue("#file_location", Arr(1))
.Parameters.AddWithValue("#dwg_description", Arr(2))
.Parameters.AddWithValue("#project_id", ProjName)
.Parameters.AddWithValue("#created_by", Arr(4))
.Parameters.AddWithValue("#created_on", dt)
End With
Try
SQLConn.Open()
If SQLConn.State = ConnectionState.Open Then
Dim ID As Integer = sqlCommand.ExecuteNonQuery()
End If
Catch ex As Exception
MsgBox(ex.Message.ToString)
Finally
SQLConn.Close()
End Try
End Using
Catch e As Exception
MsgBox (e.Message.ToString)
End Try
End Function
Rajendra Nadkar
i had written a code in C# where i had to store data from a datagrid to SQL database. I used the following code. I think it will help you.
string sqlquery = "UPDATE TableName set ColumnName1=#param1 where ColumnName2=#param2";
using (OleDbCommand Cmd = new OleDbCommand(sqlQuery, dbCon))
{
Cmd.Parameters.AddWithValue("#param1", Convert.ToDouble(dataGridView1[1, index].Value));
Cmd.Parameters.Add(new OleDbParameter("#param2", OleDbType.VarWChar)).Value = "somevalue";
updateDbCmd.ExecuteNonQuery();
updateDbCmd.Parameters.Clear();
}
Funny, I changed the field name prefix # to ? and things became smooth. In an earlier question in Feb 11, Stelian Matei suggested this edit, though later on Giezel Esteves reversed it. (Original question asked by user1176607 in Feb '10)
I guess I need to refer to documentation more thoroughly. Anyways I am giving the working code here if you or anybody interested in it.
Dim qry As String = "INSERT INTO dyn_dwg_register (`file_name` , `file_location`, `dwg_description`, `project_id`, `created_by`)" & _
" values (?file_name, ?file_location, ?dwg_description, ?project_id, ?created_by)"
Dim sqlCommand As MySqlCommand
sqlCommand = New MySqlCommand(qry, SQLConn)
sqlCommand.CommandType = CommandType.Text
With sqlCommand
.Parameters.AddWithValue("?file_name", Arr(0))
.Parameters.AddWithValue("?file_location", Arr(1))
.Parameters.AddWithValue("?dwg_description", Arr(2))
.Parameters.AddWithValue("?project_id", ProjName)
.Parameters.AddWithValue("?created_by", Arr(2))
End With

Loop through Database table and get all values of each record in turn

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

SQL and VISUAL BASIC 2008 Queries

How can I write a sql query that takes information from a database, and then put in the text in a label? I'm not really sure how to do this.
MSDN has lots of examples of getting data via ADO.NET. E.g. http://msdn.microsoft.com/library/dw70f090.
You will need to adjust the connection and command types (and the connection string) to be correct for My SQL. If you have ODBC drivers for My SQL then you can follow the ODBC example with just a change of connection string.
For using MySQL with .NET I'd recommend you this tutorial, and for your problem specially part 6, about reading the data with a MySQLDataReader.
An (almost working) sample by copy&paste from there with some changes:
Private Sub getData()
Dim conn As New MySqlConnection
Dim myCommand As New MySqlCommand
Dim myReader As MySqlDataReader
Dim SQL As String
SQL = "SELECT LabelContent FROM myTable"
conn.ConnectionString = myConnString ' your connection string here'
Try
conn.Open()
Try
myCommand.Connection = conn
myCommand.CommandText = SQL
myReader = myCommand.ExecuteReader
' loop through all records'
While myReader.Read
Dim myLabelValue as String
myLabelValue = myReader.GetString(myReader.GetOrdinal("LabelContent"))
' ... do something with the value, e.g. assign to label '
End While
Catch myerror As MySqlException
MsgBox("There was an error reading from the database: " & myerror.Message)
End Try
Catch myerror As MySqlException
MessageBox.Show("Error connecting to the database: " & myerror.Message)
Finally
If conn.State <> ConnectionState.Closed Then conn.Close()
End Try
End Sub
For selecting one column to label from ms access 2007 database just follow this step
Create ms access database for example i make name "test.accdb" and make 1 column for example column name is "ColumnName" and one table with name "Table1"
save it on whatever folder
open vb 2008 and make one form
import adodb on first writing
write this code inside class
Sub lihat()
Dim str As String = "select * from Table1"
Dim cn As New OleDb.OleDbConnection
Dim com As New OleDb.OleDbCommand
Dim adp As OleDb.OleDbDataReader
With cn
.ConnectionString = "Provider=Microsoft.ace.oledb.12.0;data source=test.accdb;persist security info=false"
.Open()
End With
With com
.Connection = cn
.CommandText = str
End With
adp = com.ExecuteReader
adp.Read()
Label1.Text = adp(1)
cn.Close()
End Sub
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
lihat()
End Sub
number 1 on adp(1) is number of column on Table1.