Actually i have a method where the user is able to choose data from excel file and choose between some headers name which are set statically and are equals to MySQL columns name in a table, then i just collect that data in a DataTable.
Now i would be able to store that data in MySQL database but which would be the best method to insert that data from a DataTable into MySQL? The rows of DataTable could contain more than 50.000/100.000 items.
That's how the DataTable could look's like (The header is choosen dynamically by the user from a combobox)
So in this Insert method which would be the best way to add that data? Should i just loop throw dataTable items and make multiple inserts?
Private Sub InsertDB()
Dim dataTable = ExcelToDT(TxtUpload.Text, ColumnHeader(PanelColumns, Column))
Dim dbCon As New Odbc.OdbcConnection
Dim conStr As String = "DSN=WRRPT"
dbCon.ConnectionString = conStr
dbCon.Open()
Dim cmd As New Odbc.OdbcCommand
With cmd
.CommandText = "INSERT INTO ? VALUES ?"
.Connection = dbCon
End With
Dim reader As Odbc.OdbcDataReader
reader = cmd.ExecuteReader
dbCon.Close()
reader = Nothing
cmd = Nothing
End Sub
Related
I have 2 servers that contain the same databases with the same structure (Main Server + Sub Server).
I deleted all data from the table in the sub server.
I got the data from the table from the main server and put it in Datatable.
I copied the data from the Datatable of the server2.
I use Dataadapter2 to update the table in the sub server.
but still, the sub server is empty?!
'Delete Data From The Sub Server
xSlConn.Open()
Dim xcmddelete As New MySqlCommand("Delete FROM tblplaces", xSlConn)
xcmddelete.ExecuteNonQuery()
'Get Data Drom The Main Server
Conn.Open()
Dim xcmd1 As New MySqlCommand("SELECT * FROM tblplaces", Conn)
Dim xdt1 As New DataTable
Dim xda1 As New MySqlDataAdapter(xcmd1)
xda1.Fill(xdt1)
'Preparing the datatable for the Sub Server
Dim xcmd As New MySqlCommand("SELECT * FROM tblplaces", xSlConn)
Dim xdt2 As New DataTable
Dim xda2 As New MySqlCommand(xcmd)
Dim xB As New MySqlCommandBuilder(xda2)
xda2.Fill(xdt2)
'Copt the data from the main datatable to the sub datatable
xdt2 = xdt1.Copy()
'Update The Datatable2
xB.GetUpdateCommand()
xda2.Update(xdt2)
xda2.Fill(xdt2)
This line of code is useless; the next line of code tosses out xdt2 anyway
xdt2 = xdt1.Copy()
This line duplicates the datatable. It won't set all the rows in xdt2 to be RowState of Added, which is what the datadapter needs them to be in order to run an insert on them
A dataadapter inspects each row's RowState. Unchanged rows are ignored. Added have the INSERT command run on them, Modified maps to UPDATE, Deleted maps to the DELETE query
Right now all the rows in your xdt1 are Unchanged because the dataadapter called AcceptChanges on them after it added them to the table
Now.. you don't need to copy the data at all; you can just set all the rows in xdt1 to be Added so the xdt2 adapter will use its INSERT command on them. Also, it should be possible to just swap the connection out on the insertcommand
'Get Data Drom The Main Server
Dim dt As New DataTable
Dim da As New MySqlDataAdapter("SELECT * FROM tblplaces", Conn)
da.Fill(dt)
Dim xB As New MySqlCommandBuilder(da)
da.InsertCommand.Connection = xSlConn
For Each ro as DataRow in xdt1.Rows
ro.SetAdded()
Next ro
da.Update(dt)
Or, you can simply request that the xda1 adapter NOT call AcceptChanges on them at all, so they will be in Added state already:
'Get Data Drom The Main Server
Dim dt As New DataTable
Dim da As New MySqlDataAdapter("SELECT * FROM tblplaces", Conn)
da.AcceptChangesDuringFill = False
da.Fill(dt)
Dim xB As New MySqlCommandBuilder(da)
da.InsertCommand.Connection = xSlConn
da.Update(dt)
Or if you're pushing to a different db
'Get Data Drom The Main Server
Dim dt As New DataTable
Dim da As New MySqlDataAdapter("SELECT * FROM tblplaces", Conn)
da.AcceptChangesDuringFill = False
da.Fill(dt)
Dim da2 as New SqliteDataAdapter("SELECT * FROM tblplaces", "put a connection string here")
Dim xB As New SqliteCommandBuilder(da2)
da2.Update(dt)
Note; this latter example uses eg SQLite as a demo of declaring two different adapters of different types for different db - it doesn't guarantee that eg the specific SQLite library you're using actually contains a dataadapter implementation (some don't)
First, you need to use Using...End Using blocks to make sure you database objects are disposed. Don't declare database connections and commands outside of the method where they are used.
Your main problem is the Fill method of the DataAdapter sets all rows to unchanged. I changed this to the DataTable.Load method which takes a parameter of LoadOption. This will preserve the RowState Added. Then when you call Update on the DataAdapter the row will be recognized. If the row is Unchanged the DataAdapter will not update the database.
Private ConStrMain As String = "Your Main server connection string"
Private ConStrSub As String = "Your Sub server connection string"
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
'Delete Data From The Sub Server
Using conSub As New MySqlConnection(ConStrSub),
cmd As New MySqlCommand("Delete FROM tblplaces", conSub)
conSub.Open()
cmd.ExecuteNonQuery()
End Using
'Retrieve data from Main server
Dim dt As New DataTable
Using conMain As New MySqlConnection(ConStrMain),
cmd As New MySqlCommand("SELECT * FROM tblplaces", conMain)
conMain.Open()
Using reader = cmd.ExecuteReader
dt.Load(reader, LoadOption.Upsert)
End Using
End Using
'Insert data from Main to Sub server
Using conSub As New MySqlConnection(ConStrSub),
da As New MySqlDataAdapter("SELECT * FROM tblplaces", conSub)
Dim sb As New MySqlCommandBuilder(da)
da.Update(dt)
End Using
End Sub
I want to be able to read a value (in this case an Group ID). All the topics and tutorials I've watched/read take the data and put it into a textbox.
I don't want to put it in a textbox in this case; I want to grab the Group ID and then say:
If Group ID = 4 then login
Here is an image of the database.
Basically, but none of the tutorials I watch or the multiple forums. None of them take a a value and say if value = 4 then login or do something else.
If text = "1" Then
MysqlConn = New MySqlConnection
MysqlConn.ConnectionString =
"server='ip of server'.; username=; password=; database="
Dim READER As MySqlDataReader
Dim member_group_id As String
Try
MysqlConn.Open()
Dim Query As String
Query = "SELECT * FROM `core_members` where name='" & TextBox2.Text & "'"
Query = "SELECT * FROM `nexus_licensekeys` where lkey_key='" & TextBox1.Text & "'"
COMMAND = New MySqlCommand(Query, MysqlConn)
READER = COMMAND.ExecuteReader
Dim count As Integer
count = 0
While READER.Read
count = count + 1
End While
Here is what I have so far. I'm kind of new implementing mysql data with visual basic and only recently started to get into it. I'm not sure what comes next or how to even start with reading the group id etc.
As I said any help from here on out would be highly appreciated of how to read the group id and say if this group id = this number then do this or that. I'm sure you get the idea.
I divided the code into UI Sub, and Data Access Function that can return data to the UI. Your Event procedure code should be rather brief and the functions should have a single purpose.
Keep your database objects local to the method. This way you can have better control. The Using...End Using blocks ensure that your database objects are closed and disposed even if there is an error.
I leave it to you to add validation code. Checking for empty TextBox or no return of records.
I hope this serves as a quick introduction to using ADO.net. The take away is:
Use Parameters
Make sure connections are closed. (Using blocks)
Private ConnString As String = "server=ip of server; username=; password=; database="
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim GroupID As String = GetGroupID(TextBox1.Text)
If GroupID = "4" Then
'your code here
End If
Dim LocalTable As DataTable = GetLicenseKeysData(TextBox1.Text)
'Get the count
Dim RowCount As Integer = LocalTable.Rows.Count
'Display the data
DataGridView1.DataSource = LocalTable
End Sub
Private Function GetGroupID(InputName As String) As String
'Are you sure member_group_id is a String? Sure looks like it should be an Integer
Dim member_group_id As String = ""
'You can pass the connection string directly to the constructor of the connection
Using MysqlConn As New MySqlConnection(ConnString)
'If you only need the value of one field Select just the field not *
'ALWAYS use parameters. See comment by #djv concerning drop table
Using cmd As New MySqlCommand("SELECT g_id FROM core_members where name= #Name")
'The parameters are interperted by the server as a value and not executable code
'so even if a malicious user entered "drop table" it would not be executed.
cmd.Parameters.Add("#Name", MySqlDbType.VarChar).Value = InputName
MysqlConn.Open()
'ExecuteScalar returns the first column of the first row of the result set
member_group_id = cmd.ExecuteScalar.ToString
End Using
End Using
Return member_group_id
End Function
Private Function GetLicenseKeysData(InputName As String) As DataTable
Dim dt As New DataTable
Using cn As New MySqlConnection(ConnString)
Using cmd As New MySqlCommand("SELECT * FROM `nexus_licensekeys` where lkey_key= #Name;", cn)
cmd.Parameters.Add("#Name", MySqlDbType.VarChar).Value = InputName
cn.Open()
dt.Load(cmd.ExecuteReader())
End Using
End Using
Return dt
End Function
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
I have made a table in mysql with attributes Product code,Quantity,company,price. And I have created a datagridview in vb 2012 and I want to take input from the form and then display the results in a datagridview. I also want to display price from the table I have created in mysql. But, i'm not able to do so.
Here is the code of my program. plz help me
Dim row As Integer = DataGridView1.Rows.Add()
Dim connection As String
Dim command As String
Dim command2 As String
command2 = "select Company from Stock WHERE Product_Code =('" + TextBox1.Text + "');"
connection = "Data Source=localhost; Database=Entry; User Id=root; Password=;"
command = "select Price from Stock WHERE Product_Code =('" + TextBox1.Text + "');"
Dim con As New MySqlConnection(connection)
Dim cmd As New MySqlCommand(command)
Dim data As DataTable
Dim adp As New MySqlDataAdapter
Dim data2 As DataTable
Dim adp2 As New MySqlDataAdapter
DataGridView1.Rows.Item(row).Cells(0).Value = TextBox1.Text
DataGridView1.Rows.Item(row).Cells(2).Value = TextBox2.Text
Try
adp = New MySqlDataAdapter(command, connection)
adp2 = New MySqlDataAdapter(command2, connection)
data = New DataTable
data2 = New DataTable
adp.Fill(data)
adp2.Fill(data2)
DataGridView1.Rows.Item(row).Cells(1).Value = data
DataGridView1.Rows.Item(row).Cells(3).Value = data
Catch ex As Exception
MessageBox.Show("Error")
End Try
You should be able to find examples of how to do this all over SO (stack overflow). But to give you a helping hand, here are the things you need to research:
First, you should parameterize your SQL to prevent injection and readability: http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.parameters.aspx
Second, you dont add rows to a datagrid, you set the datasource to something that implements IList: http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridview.datasource.aspx Then you add items to your list if you need to. If you just want to display the rows from your table, you can set the datasource to your datatable (DATA).
I made my software in vb.net and connected it with MySQL databse and using phpmyadmin I have create a table update and a column version.
In the version column I have inserted the link of version.txt
I want that my update library which is updateVB will get the link of version.txt from the database from that table....
Updatevb1.checkforupdate("Text file where your version is stated (URL)",
"Current Version",
"URL of executable updater (SFX Archive),
"Username for FTP", "Password for FTP",
showUI As Boolean)
I want to get every of these information like: Text file version URL, current version, URL of executable update etc.
How can this be done?
conn = New MySqlConnection(ServerString)
Try
conn.Open()
Dim sqlquery As String = "SELECT FROM updater"
Dim data As MySqlDataReader
Dim adapter As New MySqlDataAdapter
Dim command As New MySqlCommand
command.CommandText = sqlquery
command.Connection = conn
adapter.SelectCommand = command
data = command.ExecuteReader
While data.Read()
If data.HasRows() Then
Dim vlink As String = data(1).ToString
Dim dlink As String = data(2).ToString
Dim ftpu As String = data(3).ToString
Dim ftpp As String = data(4).ToString
End If
End While
UpdateVB1.checkforupdate("vlink", "0.0.9", "dlink", "ftpu", "ftpp", showUI:=True)
data.Close()
conn.Close()
The first problem is that your SQL statement isn't specifying any columns.
Supply the list of columns that you want to consume.
Dim sqlquery As String = "SELECT vlink, dlink, ftpu, dtpp FROM updater"