KEY cannot be null - VB.net error - mysql

I need your help, guys. I'm having an error. Please see my code below:
Imports MySql.Data.MySqlClient
Public Class frmlogin
Dim conn As MySqlConnection = New MySqlConnection
Dim serverstring As String = "Server=localhost;User Id=root;Password=root;Database=dasystem"
Dim login As Boolean
Dim ds As DataSet
Dim cusds As DataSet
Dim da As MySqlDataAdapter
Dim dt As DataTable
Dim ctrshowlogin, ctrshowsearch As Integer
Private Sub btnlogin_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnlogin.Click
Dim rowctr As Integer
Dim password As String
ctrshowlogin = 0
ds = New DataSet
da = New MySqlDataAdapter("select * from password", conn)
da.Fill(ds, "pword")
If cmbuser.SelectedItem = "Administrator" Then
For rowctr = 0 To ds.Tables(0).Rows.Count - 1
password = ds.Tables(0).Rows(rowctr).Item(0).ToString
If password = txtpass.Text Then
login = True
End If
Next (rowctr)
If login = True Then
MessageBox.Show("Login Successful!")
frmcomodities.Show()
Me.Hide()
cmbuser.Text = ""
ElseIf login = False Then
MessageBox.Show("Wrong Password, Please try again.")
txtpass.Focus()
End If
End If
End Sub
Private Sub Cancel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Cancel.Click
Close()
End Sub
End Class
Any ideas? I'm stuck with this problem. If you could help, I'd gladly appreciate it. Thanks.

You need to either change the name of the table in the da.Fill(ds, "pword") line to match the database table name (password):
da.Fill(ds, "password")
or just remove that parameter altogether
da.Fill(ds)

Related

How to show data from MySQL in TextBoxes

I need to show a set of data from MySQL like the function of DataGridView or ListView, but using multiple TextBox controls. The result of my work is that all data from a column is together on one TextBox. I don't know how to make a loop.
Code:
Imports System.Data
Imports MySql.Data.MySqlClient
Public Class Form1
Dim con As MySqlConnection = New MySqlConnection("data source=localhost; user id=root; database=abc; password=")
Dim query As String = "SELECT id,timein,timeout FROM emp"
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Using myCommand As New MySqlCommand("SELECT * FROM emp ORDER BY id ASC", con)
Try
con.Open()
Using myData = myCommand.ExecuteReader()
If myData.HasRows Then
While myData.Read()
Dim idline = String.Format("{0}", myData.GetString(myData.GetOrdinal("id")), Environment.NewLine)
Dim inline = String.Format("{0}", myData.GetString(myData.GetOrdinal("timein")), Environment.NewLine)
Dim outline = String.Format("{0}", myData.GetString(myData.GetOrdinal("timeout")), Environment.NewLine)
idbox1.Text &= idline
idbox2.Text &= idline
idbox3.Text &= idline
timein1.Text &= inline
timein2.Text &= inline
timein3.Text &= inline
timeout1.Text &= inline
timeout2.Text &= inline
timeout3.Text &= inline
End While
End If
End Using
Catch ex As Exception
MessageBox.Show(ex.ToString())
End Try
End Using
con.Close()
End Sub
End Class
This works fine with me. I got what I need to do. Thank you for the ideas.
"Imports System.Data
Imports MySql.Data.MySqlClient
Public Class Form2
Dim con As MySqlConnection = New MySqlConnection("data source=localhost; user id=root; database=abc; password=")
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim con As MySqlConnection = New MySqlConnection("data source=localhost; user id=root; database=abc; password=")
Dim query As String = "SELECT id,timein,timeout FROM emp"
con.Open()
Dim dt As New DataTable
Dim da As New MySqlDataAdapter("SELECT * FROM emp ORDER BY id ASC", con)
da.Fill(dt)
idbox1.Text = dt.Rows(0)("id").ToString()
idbox2.Text = dt.Rows(1)("id").ToString()
idbox3.Text = dt.Rows(2)("id").ToString()
timein1.Text = dt.Rows(0)("timein").ToString()
timein2.Text = dt.Rows(1)("timein").ToString()
timein3.Text = dt.Rows(2)("timein").ToString()
timeout1.Text = dt.Rows(0)("timeout").ToString()
timeout2.Text = dt.Rows(1)("timeout").ToString()
timeout3.Text = dt.Rows(2)("timeout").ToString()
con.Close()
End Sub
End Class
"
Have you tried using a DataTable? I built a form that pulls values on load from into a DataTable and in that table you can specify the columns that appear and in what order. I used the built in functions in MS VS17 RC to link the tables. Might help you out with your issue.
Private Sub Form4_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim sqlConn As New SqlConnection("Connection String Info")
Dim cmd As New SqlCommand
Dim dr As New SqlDataAdapter("-Query String-", sqlConn)
Dim dt As New DataTable
Try
If sqlConn.State = ConnectionState.Closed Then
sqlConn.Open()
dr.Fill(dt)
Menu.DisplayMember = "prod_name" --add your columns here
Menu.DataSource = dt
sqlConn.Close()
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
Order.Clear()
For Each Item As Object In Menu.SelectedItems
Order.AppendText(Item.ToString = Environment.NewLine)
Next
End Sub

Mysql DataAdapter Update Method - Doesn't Save Changes

I'm using MySQL in vb.net
Datagridview displayed correctly and everything works properly, the problem arises when I try to update the changes in the database with the update (method)
By default the data is updated in memory "is erased students with ID =" 2 ""
But in the database is not updated, I'm reading the documentation and should work with update
datosAlumnos.Update(ds, "alumnos")
Imports MySql.Data.MySqlClient
Public Class Form1
Dim con As New MySqlConnection
Dim stringCon As String = "server=localhost; user id=root; password=; database=centroeducativo"
Dim listViewAlumnos As New ListBox()
Dim ds As New DataSet()
Private Sub Form1_Load(ByVal sender As Object, _
ByVal e As System.EventArgs) Handles MyBase.Load
Try
con.ConnectionString = stringCon
con.Open()
Dim datosTablas As New MySqlDataAdapter("SHOW TABLES", con)
Dim datosAlumnos As New MySqlDataAdapter("SELECT * FROM alumnos ORDER BY Nombre", con)
Dim datosAsignaturas As New MySqlDataAdapter("SELECT * FROM asignaturas", con)
Dim datosMatriculas As New MySqlDataAdapter("SELECT * FROM matriculas", con)
datosTablas.Fill(ds, "tablas")
datosAlumnos.Fill(ds, "alumnos")
datosAsignaturas.Fill(ds, "asignaturas")
datosMatriculas.Fill(ds, "matriculas")
con.Close()
Dim tabla As DataTable
tabla = ds.Tables("tablas")
Dim fila As DataRow
Me.ListBox1.Items.Clear()
For Each fila In tabla.Rows
Me.ListBox1.Items.Add(fila.Item("Tables_in_centroeducativo"))
Next
Dim filaBorrada As DataRow() = ds.Tables("alumnos").Select("id=2")
filaBorrada(0).Delete()
datosAlumnos.Update(ds, "alumnos")
Catch ex As Exception
End Try
End Sub
Private Sub formularioTabla(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ListBox1.SelectedIndexChanged
Dim curItem As String = ListBox1.SelectedItem.ToString()
Select Case curItem
Case "alumnos"
FormularioAlumno()
Case "asignaturas"
FormularioAsignaturas()
Case "matriculas"
FormularioMatriculas()
Case Else
MsgBox("none")
End Select
End Sub
Private Sub FormularioAlumno()
Panel1.Controls.Clear()
Dim dv As DataView = ds.Tables("alumnos").DefaultView
con.Close()
Dim DataGridView As New DataGridView()
Panel1.Controls.Add(DataGridView)
DataGridView.AutoSize = True
DataGridView.DataSource = dv
DataGridView.Columns("id").Visible = False
End Sub
End Class
It seems you forget to set InsertCommand, UpdateCommand and specially Deletecommand.
To make a data adapter update data, it should have those commands. You can set those commands manually or using a MySqlCommandBuilder.
Dim myConn As New MySqlConnection("Connection String")
Dim myDataAdapter As New MySqlDataAdapter()
myDataAdapter.SelectCommand = New MySqlCommand("Select Query", myConn)
Dim myCommandBuilder As MySqlCommandBuilder = New MySqlCommandBuilder(myDataAdapter)

MySQL query (sum) not working in VB

I want to add the ages of all the employees in MySQL database column(using sum query) and then want to display its result(the value)on the click of a button in VB in a textbox.I have given a try but its not working.I am not able to figure this out.Please help....Image
Private Sub Button4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button4.Click
Dim Mysqlconn As New MySqlConnection
Mysqlconn.ConnectionString = "server=localhost;userid=root;port=85;password=andy1234;database=data"
Try
Mysqlconn.Open()
command.Connection = Mysqlconn
command.CommandText = "select sum(age) from data.etable"
Dim sqlresult As Object
sqlresult = command.ExecuteScalar
Dim str As String
str = sqlresult
TextBox5.Text = str
Mysqlconn.Close()
Catch ex As MySqlException
MessageBox.Show(ex.Message)
Mysqlconn.Dispose()
End Try
End Sub
a demo on standard port 3306 for Mysql
Schema
create table etable
( eid int auto_increment primary key,
age int not null
);
insert etable(age) values (1),(2),(3);
VB Code
Imports MySql.Data.MySqlClient
Public Class Form1
Dim conn As New MySqlConnection
Public Sub connect()
' Perform a connection test, and save ConnectionString
' in Module-level variable "conn"
Dim dbname As String = "dbname"
Dim hostname As String = "hostname"
Dim user As String = "dbuser"
Dim password As String = "password"
If Not conn Is Nothing Then conn.Close()
conn.ConnectionString = String.Format("server={0}; user id={1}; password={2}; database={3}", hostname, user, password, dbname)
Try
conn.Open()
MsgBox("Connection Test Successful")
' and ConnectionString set for subsequent queries
Catch ex As Exception
MsgBox(ex.Message)
End Try
conn.Close() ' close connection for now
End Sub
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
connect()
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim iAgeSum As Integer
Try
conn.Open()
Catch ex As Exception
End Try
Dim cmd As New MySqlCommand(String.Format("select sum(age) as ageSum from etable"), conn)
Dim result = cmd.ExecuteScalar()
If result Is Nothing Then
TextBox1.Text = "junk"
Else
iAgeSum = Convert.ToInt32(result.ToString()) ' for the purpose of showing conversion
TextBox1.Text = iAgeSum
End If
conn.Close()
End Sub
End Class
Screenshot

VB.NET: can't read database records with MySQL Data Reader dr.HasRows

when i click the button 2 with the valid ID No. on the text box it always shows the message box "Invalid ID No." but if i remove the IF statement, it shows database records and it works fine, but i need this IF statement, i think the problem here is the dr.HasRows but i don't know what to put.
Imports MySql.Data.MySqlClient
Public Class Form16
Private Sub Form16_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Dim con As New MySqlConnection("server=localhost;user id=root;password=root;database=db")
Dim DataSet1 As New DataSet
Dim dr As MySqlDataReader
Dim da As New MySqlDataAdapter
Dim cmd As New MySqlCommand
con.ConnectionString = "server = localhost; user id = root;password=root; database = db"
cmd.Connection = con
con.Open()
cmd.CommandText = "select * from voter where idn='" & TextBox1.Text & "'"
dr = cmd.ExecuteReader
con.Close()
da.SelectCommand = cmd
da.Fill(DataSet1, "db")
If dr.HasRows Then
Label2.DataBindings.Add("text", DataSet1, "db.fname")
Label10.DataBindings.Add("text", DataSet1, "db.mi")
Label11.DataBindings.Add("text", DataSet1, "db.lname")
Label12.DataBindings.Add("text", DataSet1, "db.yr")
Label13.DataBindings.Add("text", DataSet1, "db.sec")
Label14.DataBindings.Add("text", DataSet1, "db.vstatus")
Else
MessageBox.Show("Invalid ID No.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
End If
Label2.DataBindings.Clear()
Label10.DataBindings.Clear()
Label11.DataBindings.Clear()
Label12.DataBindings.Clear()
Label13.DataBindings.Clear()
Label14.DataBindings.Clear()
End Sub
End Class
You need to use Parameterized query to prevent SQL Injection
Dim commandText as String = "SELECT * FROM Voter WHERE idn=#idn"
Dim command As New MySqlCommand(commandText, connection)
command.Parameters.AddWithValue("#idn", TextBox1.Text)
You don't need to use DataSet and DataAdapter if you are using a DataReader because you could convert your DataReader to a DataTable:
dr = command.ExecuteReader() ' Get Data Reader Rows
dt.Load(dr) 'Convert DataReader into DataTable
Which now could be bind to your Label or TextBox:
Label2.DataBindings.Add("Text", dt, "fname")
You don't need then to use HasRows property to check if DataReader has rows, instead you could check the Row Count of your DataTable:
If (dt.Rows.Count > 0) Then
Label2.DataBindings.Add("Text", dt, "fname")
End If
I am also using the Using statement in dotNet specially for connection so that you don't have to close:
Using connection As New MySqlConnection(connectionString)
'More code here
End Using ' Close the connection automatically
Check Complete Code Below:
Imports MySql.Data.MySqlClient
Public Class Form16
Dim connectionString as String = "server = localhost; user id = root;password=root; database = db"
Dim dt as DataTable
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Using connection As New MySqlConnection(connectionString)
' Use Parameterized query
Dim commandText as String = "SELECT * FROM Voter WHERE idn=#idn"
Dim command As New MySqlCommand(commandText, connection)
Dim dr As MySqlDataReader
' Add idn value using parameterized query
command.Parameters.AddWithValue("#idn", TextBox1.Text)
Try
connection.Open() ' Open Connection
dr = command.ExecuteReader()
dt = New DataTable()
dt.Load(dr)
If (dt.Rows.Count > 0) Then
Label2.DataBindings.Add("Text", dt, "fname")
Label10.DataBindings.Add("Text", dt, "mi")
Label11.DataBindings.Add("Text", dt, "lname")
Label12.DataBindings.Add("Text", dt, "yr")
Label13.DataBindings.Add("Text", dt, "sec")
Label14.DataBindings.Add("Text", dt, "vstatus")
Else
MessageBox.Show("Invalid ID No.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
End If
Catch ex As Exception
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
End Using
End Sub
End Class
You have done more work than you have to...if you are going to use a datareader, your code should end up looking something like this. (I have not tested this code)
Imports MySql.Data.MySqlClient
Public Class Form16
Private Sub Form16_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Dim con As New MySqlConnection("server=localhost;user id=root;password=root;database=db")
Dim DataSet1 As New DataSet
Dim dr As MySqlDataReader
Dim da As New MySqlDataAdapter
Dim cmd As New MySqlCommand
con.ConnectionString = "server = localhost; user id = root;password=root; database = db"
cmd.Connection = con
con.Open()
cmd.CommandText = "select * from voter where idn='" & TextBox1.Text & "'"
dr = cmd.ExecuteReader
con.Close()
if dr.read then
Label2.text = dr("fname")
Label10.text = dr("mi")
Label11.text = dr("lname")
Label12.text = dr("yr")
Label13.text = dr("sec")
Label14.text = dr("vstatus")
else
MessageBox.show("Invalid ID Number")
endif
End Class

VB.NET login with a MySQL database

I do have an annoying problem here, I am not able troubleshoot this issue. My problem is that I cannot confirm my login, somewhere's a logical error because my try-catch block is not 'catching' anything, I even used breakpoints between DataBase Opening and DB.Close to see if there's any issue. Here are some screens :
So if I enter the user Gigel and his password 123 (it's encrypted) I get my false execution from my IF , 'Something's wrong out there'
Error..., anyone ?
Imports MySql.Data
Imports MySql.Data.MySqlClient
Imports System.Security.Cryptography
Public Class Form1
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Me.Close()
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim MySQLConnection As New MySqlConnection("Server = localhost;Database = users; Uid=root; Pwd = password ")
Dim HashedPass As String = ""
'Converts the Password into bytes, computes the hash of those bytes, and then converts them into a Base64 string
Using MD5hash As MD5 = MD5.Create()
System.Convert.ToBase64String(MD5hash.ComputeHash(System.Text.Encoding.ASCII.GetBytes(TextBox2.Text)))
End Using
'Counter
Dim SqlQuery As String = "SELECT COUNT(*) From users1 WHERE username = #Username AND password = #Password; "
MySQLConnection.Open()
Dim Command As New MySqlCommand(SqlQuery, MySQLConnection)
'Sanitising parameters
Command.Parameters.Add(New MySqlParameter("#Username", TextBox1.Text))
Command.Parameters.Add(New MySqlParameter("#Password", HashedPass))
'checker
If Command.ExecuteScalar() = 1 Then
MsgBox("Thanks for logging in")
Me.Hide()
Else
MsgBox("Something's wrong down there")
End If
MySQLConnection.Close()
End Sub
End Class
Try this:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Try
Dim MySQLConnection As New MySqlConnection("Server = localhost;Database = users; Uid=root; Pwd = password ")
Dim SqlQuery As String = "SELECT COUNT(*) From users1 WHERE username = #Username AND password = MD5(#Password); "
MySQLConnection.Open()
Dim Command As New MySqlCommand(SqlQuery, MySQLConnection)
Command.Parameters.Add(New MySqlParameter("#Username", TextBox1.Text))
Command.Parameters.Add(New MySqlParameter("#Password", TextBox2.Text))
If Command.ExecuteScalar() = 1 Then
MsgBox("Thanks for logging in")
Else
MsgBox("Invalid username or password")
End If
MySQLConnection.Close()
Catch ex as Exception
MsgBox(ex.Message)
End Sub