connecting the log in form in vb.net (adodb.connection usage) - mysql

I have this code in log in form, but I don't know the use of adodb.connection, please anyone help me to fix it. I don't know why the word adodb to me has an zigzag error line.
Imports System.Collections.ObjectModel
Imports System.Data
Imports System.Data.SqlClient
Public Class LoginForm1
Dim rs_login As New adodb.Recordset
Dim cn_login As New adodb.Connection
Private Sub OK_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles OK.Click
rs_login = cn_login.Execute("select * from dbo.studentinfo where [Username] = '" & UsernameTextBox.Text & "' And [Password] = '" & PasswordTextBox.Text & "'")
If rs_login.RecordCount = 0 Then
MsgBox("Invalid Username!", MsgBoxStyle.Information + MsgBoxStyle.OkOnly)
Exit Sub
Else
rs_login = cn_login.Execute("select * from dbo.USERPASS where [Username] = '" & UsernameTextBox.Text & "' And [Password] = '" & PasswordTextBox.Text & "'")
If rs_login.RecordCount = 0 Then
MsgBox("Invalid Username", MsgBoxStyle.Information + MsgBoxStyle.OkOnly)
Exit Sub
Else
user.Show()
Me.Close()
End If
End If
End Sub
Private Sub Cancel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Cancel.Click
Me.Close()
Home.Show()
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
SI.Show()
Me.Close()
End Sub
Private Sub LoginForm1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
With cn_login
.CursorLocation = ADODB.CursorLocationEnum.adUseClient
.Provider = "SQLOLEDB.1"
.CommandTimeout = 0
Dim con As New SqlConnection With {.ConnectionString = "Server=Danica-pc; database=SI;user=dandan;pwd=danica;"}
.Open()
End With
End Sub
End Class

You are using a database access code written for VBA. Probably for MS Access. In VB.NET this works very differently. You would use this Imports statement:
Imports System.Data.SqlClient
In VB.NET you would do something like this
Const StandardSecurityConnection As String = _
"Server=Danica-pc;Database=SI;User Id=dandan;Password=danica;"
Const TrustedConnection As String = _
"Server=Danica-pc;Database=SI;Trusted_Connection=True;"
Using conn As New SqlConnection(StandardSecurityConnection) 'Or TrustedConnection
Dim sql As String = _
"SELECT * FROM dbo.studentinfo WHERE Username = #usr AND Password = #pwd"
Using command As New SqlCommand(sql, conn)
command.Parameters.AddWithValue("#usr", UsernameTextBox.Text)
command.Parameters.AddWithValue("#pwd", PasswordTextBox.Text)
conn.Open()
Using dr As SqlDataReader = command.ExecuteReader()
Dim userCol AS Integer = dr.GetOrdinal("Username")
Dim pwdCol AS Integer = dr.GetOrdinal("Password")
While dr.Read()
ConSole.WriteLine("User = {0}, Password = {1}",
dr.GetString(userCol), dr.GetString(pwdCol))
End While
End Using
End Using
End Using

Related

Invalid attempt to access a field before calling Read() with MySql at answer.text = dr(1) or question.text =dr(3) when click get password

Imports MySql.Data.MySqlClient
Public Class Forgot_Password_form
Dim con As New MySqlConnection("host=localhost;username=root;password=system;database=bike")
Dim cmd As New MySqlCommand
Dim dr As MySqlDataReader
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Try
con.Open()
cmd.Connection = con
cmd.CommandText = "select * from login where userid='" & useridtxt.Text & "'and question='" & question.Text & "'and answer='" & answertxt.Text & "'"
dr = cmd.ExecuteReader
If Not dr Is Nothing Then
dr.Read()
answer.Text = dr(1)
dr.Close()
End If
Catch ex As Exception
MessageBox.Show("UserID or answer is incorrect")
End Try
con.Close()
End Sub
Private Sub Exit__Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Exit_.Click
End
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Login_Menu.Show()
Me.Hide()
End Sub
Private Sub useridtxt_LostFocus(ByVal sender As Object, ByVal e As System.EventArgs) Handles useridtxt.LostFocus
Try
con.Open()
cmd.Connection = con
cmd.CommandText = "select * from login where userid='" & useridtxt.Text & "'"
dr = cmd.ExecuteReader
If Not dr Is Nothing Then
dr.Read()
question.Text = dr(3)
dr.Close()
End If
Catch ex As Exception
End Try
End Sub
End Class

Remote database connection in VB.net not working

I'm currently working on a MySQL connection in my VB.net app. I have a form which has the following code:
Imports System.Data
Imports System.Data.SqlClient
Public Class Form4
Private Sub Form4_Load(sender As Object, e As EventArgs) Handles MyBase.Load
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
ConnectToSQL()
End Sub
Private Sub ConnectToSQL()
Dim con As New SqlConnection
Dim cmd As New SqlCommand
Dim Password As String
Dim Password2 As String
Dim userName As String
Try
If con.ConnectionString = "Network Library=DBMSSOCN;""Data Source=myserver,1433;""Initial Catalog=users;""User ID=myuser;password=mypass;" Then
con.Open()
cmd.Connection = con
cmd.CommandText = "SELECT user_username, user_pass FROM users WHERE (user_username = '" & txtUsername.Text & "' ) AND (user_pass = '" & txtPassword.Text & "')"
Dim lrd As SqlDataReader = cmd.ExecuteReader()
If lrd.HasRows Then
While lrd.Read()
Password = lrd("Password").ToString()
userName = lrd("UserName").ToString()
Password2 = txtPassword.Text()
If Password = Password2 And userName = txtUsername.Text Then
MessageBox.Show("Logged in successfully as " & userName, "", MessageBoxButtons.OK, MessageBoxIcon.Information
)
Form2.Show()
Me.Hide()
txtPassword.Text = ""
txtUsername.Text = ""
End If
End While
Else
MessageBox.Show("Username or Password incorrect...", "Authentication Failed", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
txtPassword.Text = ""
txtUsername.Text = ""
End If
End If
Catch ex As Exception
MessageBox.Show("Error while connecting to SQL Server." & ex.Message)
Finally
con.Close()
End Try
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Me.Close()
End Sub
End Class
Everytime I run the application, I enter the login details correctly and click on the sign in button (Button2). The problem is, it doesn't do anything. It doesn't throw an exception, doesn't even try to login to the server as far as I can tell. I replaced the login details with that of my own server, so that's not the problem. Did I miss something?
Don't store passwords in clear-text!
Furthermore your code is prone to sql incjection.
Nothing happens because this If will never be true:
...
If con.ConnectionString = "Network Library=DBMSSOCN;""Data Source=myserver,1433;""Initial Catalog=users;""User ID=myuser;password=mypass;" Then
...

How to read next from my database sql

I have an application of image loader, but what I want is to have a procedure for next and previous button so that I can view them one by one.
Private Sub Search_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtsearch.Click
Try
disconnect()
connect()
cmd = New Odbc.OdbcCommand("Select * FROM tblemployee WHERE lname ='" & Trim(TextBox1.Text.TrimEnd()) & "' OR fname ='" & Trim(TextBox1.Text.TrimEnd()) & "'", con)
dr = cmd.ExecuteReader
If dr.Read() Then
Dim bytBLOBData() As Byte = dr("emp_pix")
Dim stmBLOBData As New MemoryStream(bytBLOBData)
PictureBox1.Image = Image.FromStream(stmBLOBData)
Else
MessageBox.Show("No Information Record, Please Last Name only!")
End If
Catch ex As Exception
Debug.WriteLine("Please try again" & ex.Message)
End Try
End Sub
How can I manipulate for next and previous button?
Private Sub Next_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Next.Click
end sub
'Do Here
Private Sub Previous_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Previous.Click
end sub
'Do Here

System.Data.SqlClient.SqlException Unclosed quotation mark after the character string

Every time I run this code for putting some Student information, when I click to save it, there are always appear messsage in cmd.Executenonquery()..please help of this..
Imports System.Collections.ObjectModel
Imports System.Data.SqlClient
Imports System.Data
Public Class SI
Dim con As New SqlConnection With {.ConnectionString = "Server=Danica-pc; database=SI;user=dandan;pwd=danica;"}
Dim cmd As New SqlCommand
Dim query As String
Dim stuid, i As Integer
Dim studentID As Integer
Dim StudentBindingSource As Object
Dim TableAdapterManager As Object
Private Sub StudentBindingNavigatorSaveItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
Me.Validate()
Me.StudentBindingSource.EndEdit()
Me.TableAdapterManager.UpdateAll(Me.SIDataSet)
End Sub
Private Sub Label4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Kasarian.Click
End Sub
Private Sub SI_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'TODO: This line of code loads data into the 'SIDataSet.Studentinfo' table. You can move, or remove it, as needed.
Me.StudentinfoTableAdapter.Fill(Me.SIDataSet.Studentinfo)
End Sub
Private Sub getData()
i = DataGridView1.CurrentCell.RowIndex()
studentID = i
End Sub
Private Sub dataReload()
familynem.Clear()
middlenem.Clear()
givennem.Clear()
usename.Clear()
accpass.Clear()
confirmpass.Clear()
Try
Dim sql As String = "Select * from Studentinfo"
Dim myAdapter As New SqlDataAdapter(sql, con)
con.Open()
Dim myDataset As New DataSet()
myAdapter.Fill(myDataset, "SI")
DataGridView1.DataSource = myDataset
DataGridView1.DataMember = "SI"
DataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect
con.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
Private Sub famliynem_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles familynem.TextChanged
End Sub
Private Sub stat_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles stat.SelectedIndexChanged
End Sub
Private Sub HomeToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles HomeToolStripMenuItem.Click
Home.Show()
Me.Hide()
End Sub
Private Sub EventsToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles EventsToolStripMenuItem.Click
EventsForm.Show()
Me.Hide()
End Sub
Private Sub ProductsToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ProductsToolStripMenuItem.Click
Products.Show()
Me.Hide()
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cancel.Click
Home.Show()
Me.Close()
End
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles save.Click
Dim genderval As String
Dim birthdate As String
birthdate = bday.Value.ToString()
If babae.Checked = True Then
genderval = "Female"
Else
genderval = "Male"
End If
query = "insert into studentinfo(Lastname,Firstname,middlename,birthdate,gender,username)""values('" & familynem.Text & "','" & givennem.Text & "','" & middlenem.Text & "','" & birthdate & "','" & genderval & "','" & usename.text & "')"
con.Open()
cmd = New SqlCommand(query, con)
*cmd.ExecuteNonQuery()*
con.Close()
dataReload()
user.Show()
Me.Hide()
End Sub
End Class
You have an unwanted "" in this line:
query = "insert into studentinfo(Lastname,Firstname,middlename,birthdate,gender,username)""values('" & familynem.Text & "','" & givennem.Text & "','" & middlenem.Text & "','" & birthdate & "','" & genderval & "','" & usename.text & "')"
Also, I recommend that you look into using SQL parameters to pass the values:
Edit: You can use SQL parameters by replacing this code:
query = "insert into studentinfo(Lastname,Firstname,middlename,birthdate,gender,username)""values('" & familynem.Text & "','" & givennem.Text & "','" & middlenem.Text & "','" & birthdate & "','" & genderval & "','" & usename.text & "')"
con.Open()
cmd = New SqlCommand(query, con)
*cmd.ExecuteNonQuery()*
con.Close()
with:
Using conn As New SqlConnection("YOUR CONNECTION STRING")
Dim query = "INSERT INTO studentinfo(Lastname,Firstname,middlename,birthdate,gender,username) VALUES(#familynem, #givennem, #middlenem, #birthdate, #genderval, #usename)"
Using cmd As New SqlCommand(query, conn)
cmd.Parameters.AddWithValue("#familynem", familynem.Text)
cmd.Parameters.AddWithValue("#givennem", givennem.Text)
cmd.Parameters.AddWithValue("#middlenem", middlenem.Text)
cmd.Parameters.AddWithValue("#birthdate", birthdate)
cmd.Parameters.AddWithValue("#genderval", genderval.Text)
cmd.Parameters.AddWithValue("#usename", usename.Text)
conn.Open()
cmd.ExecuteNonQuery()
conn.Close()
End Using
End Using
The Using constructs take care of calling .Dispose() for you, and you should not have connections hanging around. SQL parameters help prevent SQL injection attacks, and stop the query from breaking if you have a name like O'Reilly, where the apostrophe would be a problem.

error when update data ms access using visual basic 2010

**i have simple application, but i dont know how to fix it.
this pic when i try to edit my database--> http://i861.photobucket.com/albums/ab171/gopak/sa_zps5a950df5.jpg
when i click button edit i want my access data will be update.this is my code..
thanks for your advice**
Imports System.Data.OleDb
Public Class Form2
Public cnstring As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Gop's\Downloads\admin site\admin site\admin site\bin\Debug\data_ruangan.accdb"""
Public cn As New OleDbConnection
Public cmd As New OleDbCommand
Public adaptor As New OleDbDataAdapter
Private Sub logout_btn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles logout_btn.Click
Form1.Show()
Me.Close()
End Sub
Private Sub exit_btn_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles exit_btn.Click
Dim a As Integer
a = MsgBox("Are you sure want to exit application?", vbInformation + vbYesNo, "Admin Site Virtual Tour Application")
If a = vbYes Then
End
Else
Me.Show()
End If
End Sub
Private Sub Form2_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'TODO: This line of code loads data into the 'Data_ruanganDataSet.data_ruangan' table. You can move, or remove it, as needed.
Me.Data_ruanganTableAdapter.Fill(Me.Data_ruanganDataSet.data_ruangan)
End Sub
Private Sub DataGridView1_CellClick(sender As Object, e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView1.CellClick
Dim i = DataGridView1.CurrentRow.Index
Label7.Text = DataGridView1.Item(0, i).Value
txtName.Text = DataGridView1.Item(1, i).Value
txtLocation.Text = DataGridView1.Item(2, i).Value
txtCapacity.Text = (DataGridView1.Item(3, i).Value).ToString
txtOperational.Text = (DataGridView1.Item(4, i).Value).ToString
txtInformation.Text = DataGridView1.Item(5, i).Value
End Sub
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
'If txtName.Text <> "" And txtLocation.Text <> "" And txtCapacity.Text <> "" And txtOperational.Text <> "" And txtInformation.Text <> "" Then
Dim i = DataGridView1.CurrentRow.Index
Dim ID = DataGridView1.Item(0, i).Value
Dim cmd As New OleDb.OleDbCommand
If Not cn.State = ConnectionState.Open Then
cn.Open()
End If
cmd.Connection = cn
cmd.CommandText = ("update data_ruangan set Name = '" & txtName.Text & _
"',Location = '" & txtLocation.Text & "',Capacity = '" & txtCapacity.Text & _
"',Operational_Hours ='" & txtOperational.Text & "',Information = '" & txtInformation.Text & ";")
cmd.ExecuteNonQuery()
cn.Close()
txtName.Text = ""
txtLocation.Text = ""
txtCapacity.Text = ""
txtOperational.Text = ""
txtInformation.Text = ""
'End If
End Sub
Private Sub DataGridView1_CellContentClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView1.CellContentClick
End Sub
End Class
Try to use a parameterized query to execute your code. The error message is relative to the fact that you haven't initialized your connection with the information contained in the ConnectionString.
Here an example on how to do that...... but......
Dim cmdText = "update data_ruangan set [Name] = ?,Location = ?,Capacity = ?, " & _
"Operational_Hours =?,Information = ?;"
Using cn = new OleDbConnection( cnstring )
Using cmd = OleDb.OleDbCommand(cmdText, cn)
cn.Open
cmd.Parameters.AddWithValue("#p1", txtName.Text)
cmd.Parameters.AddWithValue("#p2", txtLocation.Text)
cmd.Parameters.AddWithValue("#p3", txtCapacity.Text)
cmd.Parameters.AddWithValue("#p4", txtOperational.Text)
cmd.Parameters.AddWithValue("#p5", txtInformation.Text)
'''' WARNING ''''
' WITHOUT A WHERE STATEMENT YOUR QUERY WILL UPDATE
' THE WHOLE TABLE WITH THE SAME VALUES
'''' WARNING ''''
cmd.ExecuteNonQuery()
End Using
End Using
txtName.Text = ""
txtLocation.Text = ""
txtCapacity.Text = ""
txtOperational.Text = ""
txtInformation.Text = ""
This code updates all the records of your table with the same value, so, unless you have only one record and update Always the same record you need to add a WHERE condition to your command.
Also, the NAME word is a reserved keyword in Access 2007/2010 and it is better to encapsulate that word with square brackets to avoid a syntax error message.
I have also removed the global variable OleDbConnection and used a local one that will be closed and destroyed when the code exits from the Using statement. This is the correct way to handle disposable objects, in particular every connection object is Always to be used in this way to release as soon as possible the expensive unmanaged resource used by the object.