After adding to hosted mysql base how to read vbasic 2012 - mysql

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

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

import data from Excel to MySql using VB

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

Deleting a row from MySQL in ListView in Visual Studio 2013

I'm almost done with a trial program where I add, edit and delete stuff from my MySQL database.
But I can't seem to make the delete button to work.
Here's my code for the Delete Button:
If IDNo = Nothing Then
MsgBox("Please choose an item to delete.", MsgBoxStyle.Exclamation)
Else
Dim sqlQuery As String = "DELETE FROM tbl_adbms_test WHERE IDNo='" & IDNo & "'"
Dim sqlCommand As New MySqlCommand
With sqlCommand
.CommandText = sqlQuery
.Connection = sConnection
.ExecuteNonQuery()
End With
MsgBox("Successfully deleted an item.", MsgBoxStyle.Information)
Me.LoadPeople()
End If
The ERROR
http://stivigan.us.to/images/delete_error.jpg
And here's the rest of my Main Form.
Imports MySql.Data.MySqlClient
Public Class frm_main
Public sConnection As New MySqlConnection
Public IDNo As Integer
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
If sConnection.State = ConnectionState.Closed Then
sConnection.ConnectionString = "SERVER = localhost; USERID = root; PASSWORD = loadedro; DATABASE = adbms_test_db"
End If
LoadPeople()
End Sub
Public Sub LoadPeople()
Dim sqlQuery As String = "SELECT * FROM tbl_adbms_test"
Dim sqlAdapter As New MySqlDataAdapter
Dim sqlCommand As New MySqlCommand
Dim TABLE As New DataTable
Dim i As Integer
With sqlCommand
.CommandText = sqlQuery
.Connection = sConnection
End With
With sqlAdapter
.SelectCommand = sqlCommand
.Fill(TABLE)
End With
list_view_people.Items.Clear()
For i = 0 To TABLE.Rows.Count - 1
With list_view_people
.Items.Add(TABLE.Rows(i)("IDNo"))
With .Items(.Items.Count - 1).SubItems
.Add(TABLE.Rows(i)("LastName"))
.Add(TABLE.Rows(i)("FirstName"))
End With
End With
Next
End Sub
Private Sub btn_save_Click(sender As Object, e As EventArgs) Handles btn_add.Click
frm_add.ShowDialog()
End Sub
Private Sub btn_modify_Click(sender As Object, e As EventArgs) Handles btn_modify.Click
If IDNo = Nothing Then
MsgBox("Please choose a record to modify.", MsgBoxStyle.Exclamation)
Else
Dim sqlQuery As String = "SELECT LastName, FirstName FROM tbl_adbms_test WHERE IDNo='" & list_view_people.SelectedItems(0).Text & "'"
Dim sqlAdapter As New MySqlDataAdapter
Dim sqlCommand As New MySqlCommand
Dim sqlTable As New DataTable
With sqlCommand
.CommandText = sqlQuery
.Connection = sConnection
End With
With sqlAdapter
.SelectCommand = sqlCommand
.Fill(sqlTable)
End With
frm_modify.IDNo = list_view_people.SelectedItems(0).Text
frm_modify.LastName = sqlTable.Rows(0)("LastName")
frm_modify.FirstName = sqlTable.Rows(0)("FirstName")
frm_modify.ShowDialog()
End If
End Sub
Private Sub list_view_people_MouseClick(sender As Object, e As MouseEventArgs) Handles list_view_people.MouseClick
IDNo = list_view_people.SelectedItems(0).Text
End Sub
Private Sub btn_delete_Click(sender As Object, e As EventArgs) Handles btn_delete.Click
If IDNo = Nothing Then
MsgBox("Please choose an item to delete.", MsgBoxStyle.Exclamation)
Else
Dim sqlQuery As String = "DELETE FROM tbl_adbms_test WHERE IDNo='" & IDNo & "'"
Dim sqlCommand As New MySqlCommand
With sqlCommand
.CommandText = sqlQuery
.Connection = sConnection
.ExecuteNonQuery()
End With
MsgBox("Successfully deleted an item.", MsgBoxStyle.Information)
Me.LoadPeople()
End If
End Sub
End Class
Add Form
Public Class frm_add
Public sConnection As New MySqlConnection
Private Sub Form2_Load(sender As Object, e As EventArgs) Handles MyBase.Load
If sConnection.State = ConnectionState.Closed Then
sConnection.ConnectionString = "SERVER = localhost; USERID = root; PASSWORD = loadedro; DATABASE = adbms_test_db"
End If
End Sub
Private Sub btn_save_Click(sender As Object, e As EventArgs) Handles btn_save.Click
If sConnection.State = ConnectionState.Closed Then
sConnection.ConnectionString = "SERVER = localhost; USERID = root; PASSWORD = loadedro; DATABASE = adbms_test_db"
sConnection.Open()
End If
Dim sqlQuery As String = "INSERT INTO tbl_adbms_test(IDNo,LastName,FirstName) VALUES(NULL,'" & txt_last_name.Text & "','" & txt_first_name.Text & "')"
Dim sqlCommand As New MySqlCommand
With sqlCommand
.CommandText = sqlQuery
.Connection = sConnection
.ExecuteNonQuery()
End With
MsgBox("The data was saved.", MsgBoxStyle.Information)
Dispose()
Close()
frm_main.LoadPeople()
End Sub
End Class
Edit Form
Imports MySql.Data.MySqlClient
Public Class frm_modify
Friend IDNo As Integer
Friend LastName As String
Friend FirstName As String
Public sConnection As New MySqlConnection
Private Sub Form3_Load(sender As Object, e As EventArgs) Handles MyBase.Load
txt_last_name.Text = LastName
txt_first_name.Text = FirstName
End Sub
Private Sub btn_update_Click(sender As Object, e As EventArgs) Handles btn_update.Click
If sConnection.State = ConnectionState.Closed Then
sConnection.ConnectionString = "SERVER = localhost; USERID = root; PASSWORD = loadedro; DATABASE = adbms_test_db"
sConnection.Open()
End If
Dim sqlQuery As String = "UPDATE tbl_adbms_test SET LastName='" & txt_last_name.Text & "', FirstName='" & txt_first_name.Text & "' WHERE IDNo='" & IDNo & "'"
Dim sqlCommand As New MySqlCommand
With sqlCommand
.CommandText = sqlQuery
.Connection = sConnection
.ExecuteNonQuery()
End With
MsgBox("Record updated successfully.", MsgBoxStyle.Information)
Dispose()
Close()
frm_main.LoadPeople()
End Sub
End Class
Thanks in advance. :)
You don't have the connection open before executing the Delete command.
This is a common scenario when you keep a global connection object around in your code.
You gain nothing and there are always situations in which you end with the connection in a wrong state
You could write
Dim sqlQuery As String = "DELETE FROM tbl_adbms_test WHERE IDNo=#id"
if sConnection.ConnectionState = ConnectionState.Closed Then
sConnection.Open
End If
Dim sqlCommand As New MySqlCommand
With sqlCommand
.CommandText = sqlQuery
.Connection = sConnection
.Parameters.AddWithValue("#id", IDNo)
.ExecuteNonQuery()
End With
but I really suggest to remove your usage of the global connection object and replace it with a local MySqlConnection that will be created just when you use it and closed/destroyed after the usage. This is the intended usage of the Using Statement
Dim sqlQuery As String = "DELETE FROM tbl_adbms_test WHERE IDNo=#id"
Using con = new MySqlConnection(connstring)
Using cmd = new MySqlCommand(sqlQuery, con)
con.Open
With cmd
.Parameters.AddWithValue("#id", IDNo)
.ExecuteNonQuery()
End With
End Using
End Using
Notice also that I have removed the string concatenation in your sqlQuery and used a safer parameterized approach (albeit in this scenario and if the ListView is not editable there are no real risk of sql injection)

How to assign mysql value to a single variable in vb.net?

The following is my code for forgot password,
I want to store the value of mysql query in a variable so that i can use the variable value for placing it in a email.
Private Sub Button3_Click(sender As Object, e As EventArgs)
Handles Button3.Click
Dim p_text As String
p_text = TextBox1.Text
MsgBox(p_text)
Dim i As Integer
Try
Dim conn As MySqlConnection
conn = New MySqlConnection
conn.ConnectionString ="server=192.168.1.111;userid=betterhomes;
password=123456;database=betterhomes"
conn.Open()
Dim password As String = ""
Dim sqlquery2 As String = "SELECT bh_password FROM bh_login
where job_id = '" & p_text & "';"
Dim data2 As MySqlDataReader
Dim adapter2 As New MySqlDataAdapter
Dim command2 As New MySqlCommand
command2.CommandText = sqlquery2
command2.Connection = conn
adapter2.SelectCommand = command2
data2 = command2.ExecuteReader
While data2.HasRows
password = data2.GetString("bh_password")
MsgBox(password)
data2.Close()
End While
Catch exError As MySqlException
' MsgBox("Error connecting to database! Try again later")
End Try
End Sub
End Class
Try Like this
If data2.Read
password = data2.GetString("bh_password")
MsgBox(password)
End if
data2.Close()
Send Email
Dim mail As New MailMessage()
'set the addresses
mail.From = New MailAddress("xx#xx")
mail.[To].Add("xx#xx")
' //set the content
mail.Subject = "This is an email"
mail.Body = password
' // set the server
Dim smtp As New SmtpClient("localhost")
' // send the message
Try
smtp.Send(mail)
Response.Write("Your Email has been sent sucessfully - Thank You")
Catch exc As Exception
Response.Write("Send failure: " & exc.ToString())
End Try