the error occurs when i trigger the IF statement or if i leave the textboxes empty, the application should not close and fix the textbox problem, but it's not.
and it points at Dim i As Integer = cmd.ExecuteNonQuery()
Imports MySql.Data.MySqlClient
Public Class Form3
Public sConnection As New MySqlConnection
Private Sub Form3_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
If sConnection.State = ConnectionState.Closed Then
sConnection.ConnectionString = "server=localhost;user id=root;database=db"
sConnection.Open()
End If
LoadPeople()
End Sub
Private Sub btnsave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnsave.Click
Dim Query As String
If txtfname.Text = "" Or txtlname.Text = "" Or txtmname.Text = "" Or txtparty.Text = "" Or txtyr.Text = "" Or cmbpos.Text = "" Then
MessageBox.Show("Please complete the required fields..", "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
Else
Query = "INSERT INTO candidate(cfname,cmname,clname,cpos,cyr,cparty) VALUES('" & txtfname.Text & "','" & txtmname.Text & "','" & txtlname.Text & "','" & cmbpos.Text & "','" & txtyr.Text & "','" & txtparty.Text & "')"
End If
Dim cmd As MySqlCommand = New MySqlCommand(Query, sConnection)
Dim i As Integer = cmd.ExecuteNonQuery()
If (i > 0) Then
MsgBox("Record Inserted")
Else
MsgBox("Record is not Inserted")
End If
sConnection.Close()
txtfname.Text = ""
txtlname.Text = ""
txtmname.Text = ""
txtparty.Text = ""
txtyr.Text = ""
cmbpos.Invalidate()
txtfname.Focus()
LoadPeople()
End Sub
I would use a try catch....
Try
cmd.ExecuteNonQuery()
MsgBox("Record Inserted")
Catch ex as Exception
MsgBox("Error:" & ex.message)
Finally
'Optional but I would use it to close of DB Connections
End Try
You are also vunerable to SQL Injections....use paramaterised SQL or other methods to limit risks.
Related
i'm new learning visual studio. and i get an error
Connection property has not been initialized
This my code:
Imports System.Data.SqlClient
Public Class Form1
Dim con As SqlConnection
Dim cm As SqlCommand
Dim dr As SqlDataReader
Private Sub CheckBox1_CheckedChanged(sender As Object, e As EventArgs) Handles CheckBox1.CheckedChanged
If CheckBox1.Checked Then
TextBox2.PasswordChar = ""
Else
TextBox2.PasswordChar = "•"
End If
End Sub
Private Sub Form1_Load(ByVal sender As Object, e As EventArgs) Handles MyBase.Load
TextBox1.MaxLength = 50
TextBox2.PasswordChar = "•"
End Sub
Private Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button1.Click
If TextBox1.Text = "" Or TextBox2.Text = "" Then
MsgBox("pls fill the data", MsgBoxStyle.Information)
Exit Sub
Else
Call Koneksi()
cm = New SqlCommand("select*from login where username='" & TextBox1.Text & "'and password" & TextBox2.Text & "'", con)
cm.Connection = con
dr = cm.ExecuteReader
dr.Read()
last.Show()
Me.Close()
If dr.HasRows Then
MsgBox("succes", MsgBoxStyle.Information, "information")
Else
MsgBox("wrong password/username", MsgBoxStyle.Critical)
TextBox1.Clear()
TextBox2.Clear()
End If
End If
End Sub
End Class
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()
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
Imports MySql.Data.MySqlClient
Public Class Form1
Dim MysqlConn As MySqlConnection
Dim COMMAND As MySqlCommand
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Me.BrandsTableAdapter.Fill(Me.StoreDataSet.brands)
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
MysqlConn = New MySqlConnection
MysqlConn.ConnectionString =
"server=localhost;userid=root;password=;database=brands"
Dim READER As MySqlDataReader
Try
MysqlConn.Open()
Dim Query As String
Query = "insert into database.brands(id,name,,created_at,updated_at) values ('" & TextBox1.Text & "','" & TextBox2.Text & "','" & TextBox3.Text & "','" & TextBox4.Text & "')"
COMMAND = New MySqlCommand(Query, MysqlConn)
READER = COMMAND.ExecuteReader
MessageBox.Show("Data saved")
MysqlConn.Close()
Catch ex As MySqlException
MessageBox.Show(ex.Message)
Finally
MysqlConn.Dispose()
End Try
End Sub
End Class
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