import data from Excel to MySql using VB - mysql

Imports System.Data.Odbc
Imports System.Data.Sql
Imports System.Data.SqlClient
Imports MySql.Data
Imports MySql.Data.MySqlClient
Imports ADODB
.
.
.
Protected Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Try
Dim conn As New OdbcConnection
Dim rset As New DataSet
Dim buff0 As String
Dim buff1 As String
Dim buff2 As String
Dim filePath As String = "C:\\Book3.xls"
conn.ConnectionString = "Driver={Microsoft Excel Driver (*.xls, *.xlsx, *.xlsm, *.xlsb)};DriverId=790;Dbq=" & filePath & ";" 'Driver={Microsoft Excel Driver (*.xls)};DriverId=790;Dbq=d:\temp\test.xls;"
conn.Open()
rset.Open("select * from [Sheet1$]", conn, CursorTypeEnum.adOpenForwardOnly)
Do Until rset.EOF
buff0 = rset(0).Value
buff1 = rset(1).Value
buff2 = rset(2).Value
MySqlCmd = New MySqlCommand
MySqlCmd.Connection = Myconnect
MySqlCmd.CommandText = "INSERT INTO customers VALUES('" & buff0 & "','" & buff1 & "','" & buff2 & "')"
MySqlCmd.ExecuteNonQuery()
rset.MoveNext()
Loop
MsgBox("Import Successful!", MsgBoxStyle.Information, Title:="SOMS")
Catch ex As Exception
MsgBox("Import Unsuccessful!", MsgBoxStyle.Critical, Title:="SOMS")
End Try
End Sub
I am trying to import data from excel to mysql using this code got from web. But getting some errors. Give me suggestion where i am going wrong. I am very newbe for ADO,OLE. here i am using ODBC for reading data from excel and for insert I use mysql native driver. Another question is, Am i going in right direction or otherways possible?

Try this code and tell me :
Private Sub SimpleButton1_Click(sender As Object, e As EventArgs) Handles SimpleButton1.Click
Dim dialog As New OpenFileDialog()
dialog.Filter = "Excel files |*.xls;*.xlsx"
dialog.InitialDirectory = "C:\"
dialog.Title = "Select file for import"
If dialog.ShowDialog() = DialogResult.OK Then
Dim dt As DataTable
Dim buff0 As String
Dim buff1 As String
Dim buff2 As String
dt = ImportExceltoDatatable(dialog.FileName)
For i = 0 To dt.Rows.Count - 1
buff0 = dt.Rows(i)(0)
buff1 = dt.Rows(i)(1)
buff2 = dt.Rows(i)(2)
MySqlCmd = New MySqlCommand
MySqlCmd.Connection = Myconnect
MySqlCmd.CommandText = "INSERT INTO customers VALUES('" & buff0 & "','" & buff1 & "','" & buff2 & "')"
MySqlCmd.ExecuteNonQuery()
Next
End If
End Sub
Public Shared Function ImportExceltoDatatable(filepath As String) As DataTable
' string sqlquery= "Select * From [SheetName$] Where YourCondition";
Dim dt As New DataTable
Try
Dim ds As New DataSet()
Dim constring As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & filepath & ";Extended Properties=""Excel 12.0;HDR=YES;"""
Dim con As New OleDbConnection(constring & "")
con.Open()
Dim myTableName = con.GetSchema("Tables").Rows(0)("TABLE_NAME")
Dim sqlquery As String = String.Format("SELECT * FROM [{0}]", myTableName) ' "Select * From " & myTableName
Dim da As New OleDbDataAdapter(sqlquery, con)
da.Fill(ds)
dt = ds.Tables(0)
Return dt
Catch ex As Exception
MsgBox(Err.Description, MsgBoxStyle.Critical)
Return dt
End Try
End Function

Related

registration form encryption using vb.net and mysql

I have a registration form and I want to encrypt the password using whatever encryption is available, I'm using vb.net 2008 and MySQL as database, I searched through online and found some encrypting code but I have no idea how to connect it to my registration form. here is my registration code and the encryption code i found online (at the top part)
Imports MySql.Data.MySqlClient
Imports System.Security
Imports System.Security.Cryptography
Public Class user
Public Function AES_Encrypt(ByVal input As String, ByVal pass As String) As String
Dim AES As New System.Security.Cryptography.RijndaelManaged
Dim Hash_AES As New System.Security.Cryptography.MD5CryptoServiceProvider
Dim encrypted As String = ""
Try
Dim hash(31) As Byte
Dim temp As Byte() = Hash_AES.ComputeHash(System.Text.ASCIIEncoding.ASCII.GetBytes(pass))
Array.Copy(temp, 0, hash, 0, 16)
Array.Copy(temp, 0, hash, 15, 16)
AES.Key = hash
AES.Mode = Security.Cryptography.CipherMode.ECB
Dim DESEncrypter As System.Security.Cryptography.ICryptoTransform = AES.CreateEncryptor
Dim Buffer As Byte() = System.Text.ASCIIEncoding.ASCII.GetBytes(input)
encrypted = Convert.ToBase64String(DESEncrypter.TransformFinalBlock(Buffer, 0, Buffer.Length))
Return encrypted
Catch ex As Exception
End Try
End Function
Private Sub BCreateAcount_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BCreateAcount.Click
Dim conn As MySqlConnection
conn = New MySqlConnection
conn.ConnectionString = "server = localhost;username= root;password= a;database= database"
Try
conn.Open()
Catch mali As MySqlException
MsgBox("connot establish connection")
End Try
Dim myCommand As New MySqlCommand
Dim myReader As MySqlDataReader
myCommand.Connection = conn
myCommand.CommandText = "insert into user values('" + txtUserName.Text + "','" + txtNewPassword.Text + "')"
Call calldaw()
If txtUserName.Text = "" Or txtNewPassword.Text = "" Or txtConfirmPassword.Text = "" Then
MsgBox("Please enter username and password", MsgBoxStyle.Information, "Inventory System")
ElseIf txtConfirmPassword.Text = txtNewPassword.Text Then
MsgBox("Account Created", MsgBoxStyle.Information, "Inventory System")
myReader = myCommand.ExecuteReader()
txtUserName.Text = ""
txtNewPassword.Text = ""
txtConfirmPassword.Text = ""
Else
MsgBox("Password did not match", MsgBoxStyle.Critical, "Inventory System")
txtConfirmPassword.Text = ""
txtNewPassword.Text = ""
txtUserName.Text = ""
End If
End Sub
Private Sub calldaw()
Dim conn As MySqlConnection
conn = New MySqlConnection
conn.ConnectionString = "server = localhost;username= root;password= a;database= database"
Try
conn.Open()
Catch mali As MySqlException
MsgBox("connot establish connection")
End Try
Dim myData As MySqlDataAdapter
Dim reason As String = " Create Account "
Dim tao As String = "admin"
myData = New MySqlDataAdapter
Dim sqlsql = "insert into daily_log values('" + tao + "','" + Date1.Text + "','" + reason + "','" + Time1.Text + "')"
Dim ssql = "Select * from user"
Dim myCommand As New MySqlCommand
myCommand.Connection = conn
myCommand.CommandText = sqlsql
Dim myReader As MySqlDataReader
myReader = myCommand.ExecuteReader
End Sub
Private Sub BBack_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BBack.Click
Me.Close()
End Sub
Private Sub user_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Timer1.Enabled = True
End Sub
Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
Date1.Text = Date.Today.Date
Dim Date2 As Date = Date1.Text
Date1.Text = Format(Date2, "yyyy-MM-dd")
Time1.Text = TimeOfDay
End Sub
End Class
any help will do, thanks.
You have to call the AES_Encrypt function before executing the INSERT statement in order to pass the encrypted password to database.
Dim myCommand As New MySqlCommand
Dim myReader As MySqlDataReader
myCommand.Connection = conn
myCommand.CommandText = "insert into user values('" + txtUserName.Text + "','" + AES_Encrypt(txtNewPassword.Text,txtNewPassword.Text) + "')"
Call calldaw()

Connection must be valid and open VB.net error using vb.net

This is my code for read data from EXCEL file using ODBC driver and write in MySql Database.
Public Class WebForm3
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim MySqlCmd = New SqlCommand()
' Dim dialog As New System.Windows.Forms.OpenFileDialog()
'Dim dialog As New OpenFileDialog()
'dialog.Filter = "Excel files |*.xls;*.xlsx"
'dialog.InitialDirectory = "C:\"
'dialog.Title = "Select file for import"
'If dialog.ShowDialog() = DialogResult.OK Then
Try
Dim dt As DataTable
Dim buff0 As String
Dim buff1 As String
Dim buff2 As String
dt = ImportExceltoDatatable("C:\\Book1.xls")
For i = 0 To dt.Rows.Count - 1
buff0 = dt.Rows(i)(0)
buff1 = dt.Rows(i)(1)
buff2 = dt.Rows(i)(2)
Dim connStr As String = "server=localhost;user=root;database=ajaxsamples;port=3306;password=innoera;"
Dim connMysql As MySqlConnection = New MySqlConnection(connStr)
Dim sql As String = "INSERT INTO ajaxsamples.customers VALUES('" & buff0 & "','" & buff1 & "','" & buff2 & "')"
Dim cmd As MySqlCommand = New MySqlCommand(sql, connMysql)
cmd.ExecuteNonQuery()
cmd.Dispose()
connMysql.Close()
Next
Catch ex As Exception
MsgBox(Err.Description, MsgBoxStyle.Critical)
End Try
'End If
End Sub
Public Shared Function ImportExceltoDatatable(filepath As String) As DataTable
' string sqlquery= "Select * From [SheetName$] Where YourCondition";
Dim dt As New DataTable
Try
Dim ds As New DataSet()
Dim constring As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & filepath & ";Extended Properties=""Excel 12.0;HDR=YES;"""
Dim con As New OleDbConnection(constring & "")
con.Open()
Dim myTableName = con.GetSchema("Tables").Rows(0)("TABLE_NAME")
Dim sqlquery As String = String.Format("SELECT * FROM [{0}]", myTableName)
'Dim myTableName = con.GetSchema("Tables").Rows(0)("TABLE_NAME")
'Dim sqlquery As String = String.Format("SELECT * FROM Sheet1$") ' "Select * From " & myTableName
Dim da As New OleDbDataAdapter(sqlquery, con)
da.Fill(ds)
dt = ds.Tables(0)
Return dt
Catch ex As Exception
MsgBox(Err.Description, MsgBoxStyle.Critical)
Return dt
End Try
End Function
End Class
I got this error,
"Connection must be valid and open "
whats wrong in code? I am newbie for VB. Any help would be appreciated.
You forgot to open your connection.
Try
connMysql = New MySqlConnection
connMysql.ConnectionString = connStr
connMysql.Open() 'You forgot to open your connection
sql = "SELECT * FROM users"
cmd = New MySqlCommand(sql, connMysql)
cmd.ExecuteNonQuery()
cmd.Dispose()
Catch ex As Exception
'your error code here
Finally
connMysql.Close() 'close your connection
End Try

After adding to hosted mysql base how to read vbasic 2012

I'm working on simple project to figure out how databases work.
I created mysql base on my host and used this code to connect to it
Private mysql_host = "myhost"
Private mysql_user = "myuser"
Private mysql_pass = "mypw"
Private mysql_db = "mydb"
Private SQLConnect As String = "Server=" + mysql_host + ";" + "User Id=" + mysql_user + ";" + "Password=" + mysql_pass + ";" + "Database=" + mysql_db
Private SQLConnection As New MySqlConnection
Private Sub Form1_Load(sender As Object, e As System.EventArgs) Handles Me.Load
sqlConnection.ConnectionString = SQLConnect
Try
If sqlConnection.State = ConnectionState.Closed Then
sqlConnection.Open()
MsgBox("Connected")
Else
sqlConnection.Close()
MsgBox("Not Connected")
End If
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
After that i used this code to add record into database.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim SQLStatement As String = "INSERT into tCodes(Code) VALUES ('" & TextBox1.Text & "')"
Dim cmd As New MySqlCommand
With cmd
.CommandText = SQLStatement
.CommandType = CommandType.Text
.Connection = SQLConnection
.ExecuteNonQuery()
End With
MsgBox("Added")
End Sub
On the other form i want to check if record exist in database. How to do that .
I tried with code
Dim SQLStatement As String = "SELECT * From tCodes WHERE Code '" & TextBox1.Text & "'")
For read . Me using this
Private host As String = "host" 'Host DB
Private user As String = "user" 'User DB
Private pass As String = "pass" 'Pass DB
Private base As String = "base" 'Base
Private conn As String = "Database=" & base & ";Data Source=" & host & ";User Id=" & _
user & ";Password=" & pass 'Connection
Private Connection As New MySqlConnection(conn) 'Connection
Private readData As MySqlDataReader 'Data Reader
Private adaptsData As New MySqlDataAdapter 'Data Adapter
Private command As New MySqlCommand 'command
Private ds As New DataSet 'DataSet
After
Public Function __select(Optinal table as String = "tCodes") As String
Try
Connection.Open()
Dim query As String = "SELECT * FROM " & table
command.CommandText = query
command.Connection = conexiune
adaptsData.SelectCommand = comanda
adaptsData.Fill(ds, tabla)
Dim newvalue As String = ds.Tables(tabla).Rows(0).Item(item)
ds.Dispose()
ds.Clear()
Connection.Close()
Return newvalue
Catch ex As Exception
ds.Dispose()
ds.Clear()
conexiune.Close()
msgbox(ex.message)
End Try
End Function
Dim conn As MySqlConnection
Dim sqlquery = "SELECT * FROM tCodes WHERE Code = '" + txtCode.Text + "'"
Dim myCommand As New MySqlCommand()
myCommand.Connection = conn
myCommand.CommandText = sqlquery
'start query
myAdapter.SelectCommand = myCommand
Dim myData As MySqlDataReader
myData = myCommand.ExecuteReader()
'see if user exists
If myData.HasRows = 0 Then
MsgBox("Kod je nevazeci")
conn.Close()
Else
MsgBox("Kod je vazeci")
End If
That was the solution of this problem

What is wrong in this code Vb MySql data to TextBox

What is wrong in this code
I run the software click the button and nothing happens if you have a better code that would help thanks in advance
Dim sql As String
Dim con As MySqlConnection = New
MySqlConnection("Server=localhost;Database=******;Uid=*****;password =******")
Dim ds As DataSet = New DataSet
Dim dataadapter As MySqlDataAdapter = New MySqlDataAdapter
Dim cmd As MySqlCommand = New MySqlCommand()
Dim datareader As MySqlDataReader
Try
sql = "SELECT * FROM users"
con.Open()
cmd.CommandText = sql
cmd.Connection = con
dataadapter.SelectCommand = cmd
datareader = cmd.ExecuteReader
While datareader.Read
datareader.Read()
Email.Text = datareader("Email")
LastName.Text = datareader("LastName")
Address.Text = datareader("Address")
End While
Catch ex As Exception
End Try
con.Close()
End Sub
Narrow the scope of your select. The way its written I think it might set the textbox 100 times if 100 results are returned. Here is how I would write this:
Imports MySql.Data.MySqlClient
Public Sub getData()
Dim objConn As MySqlConnection = New MySqlConnection("Data Source=localhost;" _
& "Database=TestDB;" _
& "User ID=Root;" _
& "Password=myPassword;")
Dim strSQL As String = "SELECT TOP 1 Email, LastName, Address FROM users"
Dim da As MySql.Data.MySqlClient.MySqlDataAdapter
Dim dt As New DataTable
Try
objConn.Open()
da = New MySql.Data.MySqlClient.MySqlDataAdapter(strSQL, objConn)
da.Fill(dt)
If dt.Rows.Count > 0 Then
Email.Text = dt.Rows(0)("Email").ToString
LastName.Text = dt.Rows(0)("LastName").ToString
Address.Text = dt.Rows(0)("Address").ToString
End If
da = Nothing
objConn.Close()
objConn = Nothing
Catch ex As Exception
objConn.Close()
objConn = Nothing
End Try
End Sub

save and retrive image from mysql using vb.net

This code is now working. i want to save an image in database please help me how i can work on this
Private Sub Button1_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
OpenFileDialog1.ShowDialog()
TextBox1.Text = OpenFileDialog1.FileName
CaptionTextBox.Text = OpenFileDialog1.SafeFileName
' ImagePictureBox.Image = image.FromFile(TextBox1.Text)
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
updateRecord("insert into uploadimages(caption,image) values('" + CaptionTextBox.Text + "', '#ImagePictureBox' )")
End Sub
Imports MySql.Data.MySqlClient
Imports System.Drawing.Imaging
Dim cn As New MySqlConnection
Dim con As New MySqlConnection
Dim cmd As New MySqlCommand
Dim dr As MySqlDataReader
Dim da As MySqlDataAdapter
Dim dt As New DataTable
Dim abc As String
private sub from1()
cn.ConnectionString = "Server=localhost; user id=root; password=; database = school"
cmd.Connection = cn
cn.Open()
end sub
Private Sub images()
Dim arrImage() As Byte
Dim strImage As String
Dim myMs As New IO.MemoryStream
If Not IsNothing(Me.PictureBox5.Image) Then
Me.PictureBox5.Image.Save(myMs, Me.PictureBox5.Image.RawFormat)
arrImage = myMs.GetBuffer
strImage = "1000"
Else
arrImage = Nothing
strImage = "NULL"
End If
cmd.CommandText = "INSERT INTO admision(name, photo) VALUES('" & Me.TextBox1.Text & "'," & _
strImage & ")"
If strImage = "1000" Then
cmd.Parameters.Add(strImage, MySqlDbType.Blob).Value = arrImage
End If
MsgBox("Data save successfully!")
clear()
cmd.ExecuteNonQuery()
cn.Close()
End Sub