Gå til innhold

[2008] MySQL - Problemer med kode, MD5 hasing, hente / skrive til MySQL


Anbefalte innlegg

Hei!

Lager et program som skal connecte en database som kjører MySQL.

Min form har en 2 tekstbokser (1: txtPassword & 2: txtBrukernavn) en login knapp (1: btnLogin) så koden min ser slik ut:

 

Imports MySql.Data.MySqlClient

Imports System.Data

Public Class Form1

 

   Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

       Dim conn As MySqlConnection

      

'connect to DB

       conn = New MySqlConnection()

       conn.ConnectionString = "server=******; user id=*****; password=*****; database=*****"

       

'see if connection failed.

       Try

           conn.Open()

       Catch myerror As MySqlException

           MessageBox.Show("Error Connecting to Database: " & myerror.Message)

       End Try

   End Sub

 

   Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnLogin.Click

      

' SQL query

       Dim conn As MySqlConnection

       Dim myAdapter As New MySqlDataAdapter

       Dim sqlquery = "SELECT Username, Password FROM userlist Where Username='" & txtBrukernavn.Text & "' and Password='" & txtPassord.Text & "'"

       Dim myCommand As New MySqlCommand()

       myCommand.Connection = conn

       myCommand.CommandText = sqlquery

       

'start query

       myAdapter.SelectCommand = myCommand

       Dim myData As MySqlDataReader

       myData = myCommand.ExecuteReader()   'HER FÅR JEG EN ERROR!

       

'see if user exits.

       If myData.HasRows = 0 Then

           MessageBox.Show("Invalid Login Details", "Login Error", MessageBoxButtons.OK, MessageBoxIcon.Error)

       Else

           Dim frm1 = New Form1

           frm1.Show()

           Me.Visible = False

       End If

   End Sub

End Class

 

Så jeg får en error der jeg skrevet det. Kan noen titte igjennom koden å se om de finner noen feil? Evnt. gjøre den ryddigere eller andre ting!

 

Takk!

 

EDIT:

 

Ønsker også MD5 hashing inn i koden, med registrering`s knapp og jeg må godkjenne brukeren.

Endret av Gjest
Lenke til kommentar
Videoannonse
Annonse

For også en annen error :p

' SQL query

Dim conn As MySqlConnection

Dim myAdapter As New MySqlDataAdapter

Dim sqlquery = "SELECT Username, Password FROM userlist Where Username='" & txtBrukernavn.Text & "' and Password='" & txtPassord.Text & "'"

Dim myCommand As New MySqlCommand()

myCommand.Connection = conn

myCommand.CommandText = sqlquery

 

det som er uthevet får jeg en annen error som sier:

"Variable 'conn' is used before it has assigned a value. A null reference exception could result at runtime"

Hvor er den brukt før?

 

Den andre error'en sier:

"InvalidOperationException was unhandled - Connection must be valid or open"

Tror det har noe med MySQL.Data som jeg har importert

Lenke til kommentar

Noe slikt:

Public conn As MySqlConnection

Aldri brukt det med public før "/

 

EDIT:

Det var riktig :D

Da var "Conn" problemet løst

Takk!

 

Neste problem:

'start query
   myAdapter.SelectCommand = myCommand
   Dim myData As MySqlDataReader
   myData = myCommand.ExecuteReader()   'HER FÅR JEG EN ERROR!

 

Det står som error:

"InvalidOperationException was unhandled - Connection must be valid or open"

Tror det har noe med MySQL.Data som jeg har importert

 

 

EDIT 2:

Testet koden på nytt nå da fikk jeg beskjed at databasen ikke finnes så det må jeg rette opp!

Jeg må bare si TUSEN TAKK FOR HJELPEN Gnålern!

 

EDIT 2:

Nå vil jeg lage registrering`s knapp + MD5 hashing av passord!

Endret av Gjest
Lenke til kommentar

For å rydde opp!

----

 

Det jeg trenger hjelp med nå:

 

#1 MD5 hasing for registrere brukere i databasen.

#2 Lage en kode for registrering det vil si at du skal kunne fylle ut: Username, Password og Mail.

#3 Lage en member for der du skal kunne endre dit nåværende passord og mail. + At det skal stå: "Velkommen: (brukernavnet til innloggede bruker skal så her)

#5 Admin form der jeg EaK2k skal kunne endre ALLE brukere som er i databasen. Googlet litt og så at jeg skal bruke DataGrid, er det riktig?

#6 Endre på om brukeren er bannet eller, det vil si at hvis det står i databasen:

Username: EaK2k

Password: *****

E-Mail: *****@******.com

Banned: Yes

Yes = Kan ikke logge inn

No = Kan logge inn.

 

Takk :D

Lenke til kommentar
#1 MD5 hasing for registrere brukere i databasen.

Dim pwd As String = "ettslagspassordkanensi";
Dim data As Byte() = System.Text.Encoding.UTF8.GetBytes(pwd)
Dim hash As Byte()
Dim md5 As System.Security.Cryptography.MD5 = System.Security.Cryptography.MD5.Create()
hash = md5.ComputeHash( data )

 

Da ligger MD5 hashen i hash, denne er 128-bit eller 256-bit (altså 16- eller 32-byte)

Les dokumentasjon for MD5 på MSDN for mere informasjon om dette.

De andre punktene må du klare selv.

Lenke til kommentar

Takk for MD5 hashinga, nå må jeg bare få den til å funke med registreringen som jeg ikke klarer. (Har NULL kode)

----

Som sagt trenger forsatt hjelp til dette:

 

 

#1 MD5 hasing for registrere brukere i databasen.

#2 Lage en kode for registrering det vil si at du skal kunne fylle ut: Username, Password og Mail.

#3 Lage en member for der du skal kunne endre dit nåværende passord og mail. + At det skal stå: "Velkommen: (brukernavnet til innloggede bruker skal så her)

#5 Admin form der jeg EaK2k skal kunne endre ALLE brukere som er i databasen. Googlet litt og så at jeg skal bruke DataGrid, er det riktig?

#6 Endre på om brukeren er bannet eller, det vil si at hvis det står i databasen:

Username: EaK2k

Password: *****

E-Mail: *****@******.com

Banned: Yes

Yes = Kan ikke logge inn

No = Kan logge inn.

 

 

Har funnet 2 koder her, tenkte å bruke den første koden til å hente ut data fra databasen hvis den fungerer da:

imports System.Data.Odbc

 

Dim cn as odbcConnection = new odbcconnection(provider & path to the

database)

Dim sql as string = SELECT * FROM tablename"

Dim cmd as odbcCommand = New odbcCommand(sql,cn)

Dim da as odbcDataAdapter = New odbcDataAdapter

da.SelectCommand = cmd

dim ds as New DataSet

da.Fill(ds)

 

control.DataBindings.Add("Text", ds, "tablename.fieldname")

 

Denne skal jeg bruke til å skrive til databasen:

Set MyRecSet1 = MyConn.Execute("INSERT INTO ID_ProjectNo (ProjectNo, CustomerName, Machine) VALUES (CInt(txtAddProjectNumber.text),txtAddCustomerName.text,txtAddMachine.text)")
Endret av Gjest
Lenke til kommentar

Hei!

Har funnet noen koder her:

 

 

Insert Data into Access Database through OleDbConnection

 

 

Imports System

Imports System.Data

Imports System.Data.SqlClient

Imports System.Collections

Imports System.Windows.Forms

Imports System.Resources

 

Public Class MainClass

   Shared Dim OleDbConnection As System.Data.OleDb.OleDbConnection

   Shared Dim AddressBookDataAdapter As System.Data.OleDb.OleDbDataAdapter

 

   Shared Sub Main()

      Connect()

      Display()

      

      Dim OleDbUpdateCommand As System.Data.OleDb.OleDbCommand

      OleDbUpdateCommand = new System.Data.OleDb.OleDbCommand

      

      OleDbUpdateCommand.CommandText = _

              "Insert into Employee (ID, FirstName, LastName) values" & _

              "(1,'Joe','Yin')"

              

      OleDbUpdateCommand.Connection = OleDbConnection

 

      AddressBookDataAdapter.UpdateCommand = OleDbUpdateCommand

 

 

      AddressBookDataAdapter.UpdateCommand.ExecuteNonQuery()

 

 

      Display()

      Disconnect()

   End Sub

 

   Shared Sub Display()

      Dim OleDbSelectCommand As System.Data.OleDb.OleDbCommand

      OleDbSelectCommand = New System.Data.OleDb.OleDbCommand()

 

      OleDbSelectCommand.CommandText = "SELECT ID, FirstName, LastName,Salary FROM Employee"

      OleDbSelectCommand.Connection = OleDbConnection

 

      AddressBookDataAdapter = New System.Data.OleDb.OleDbDataAdapter()

 

      AddressBookDataAdapter.SelectCommand = OleDbSelectCommand

 

 

      Dim AddressBookDataSet As System.Data.DataSet

      AddressBookDataSet = New System.Data.DataSet()

      CType(AddressBookDataSet, System.ComponentModel.ISupportInitialize).BeginInit()

 

      AddressBookDataAdapter.Fill(AddressBookDataSet)

 

 

        Dim dataTable As DataTable = AddressBookDataSet.Tables(0)

 

        ' ensure dataTable not empty

        If dataTable.Rows.Count <> 0 Then

           Dim recordNumber As Integer = Convert.ToInt32(dataTable.Rows(0)(0))

 

           Console.Write( recordNumber.ToString & "  ")

           Console.Write( Convert.ToString(dataTable.Rows(0)(1)) & "  ")

           Console.Write( Convert.ToString(dataTable.Rows(0)(2)) & "  ")

           Console.Write( Convert.ToString(dataTable.Rows(0)(3)) & "  ")

 

           ' display not-found message

        Else

           Console.WriteLine( "No record found" )

        End If

        Console.WriteLine(  )

   End Sub

 

   Shared Sub Connect()

     OleDbConnection = New System.Data.OleDb.OleDbConnection()

 

     OleDbConnection.ConnectionString = _

        "Provider=Microsoft.Jet.OLEDB.4.0;Password="""";" & _

        "User ID=Admin;Data Source=Employee.mdb;Mode=Sha" & _

        "re Deny None;Extended Properties="""";" & _

        "Jet OLEDB:System database="""";Jet OLEDB:Regis" & _

        "try Path="""";Jet OLEDB:Database Password="""";" & _

        "Jet OLEDB:Engine Type=5;Jet OLEDB:Dat" & _

        "abase Locking Mode=1;Jet OLEDB:Global Partial " & _

        "Bulk Ops=2;Jet OLEDB:Global Bulk T" & _

        "ransactions=1;Jet OLEDB:New Database " & _

        "Password="""";Jet OLEDB:Create System Databas" & _

        "e=False;Jet OLEDB:Encrypt Database=False;" & _

        "Jet OLEDB:Don't Copy Locale on Compact=" & _

        "False;Jet OLEDB:Compact Without Replica " & _

        "Repair=False;Jet OLEDB:SFP=False"

 

 

     Try

        OleDbConnection.Open()

     Catch ex As Exception

        Console.WriteLine(ex.Message)

     End Try

   End Sub

 

   Shared Sub Disconnect()

     Try

        OleDbConnection.Close()

     Catch ex As Exception

        Console.WriteLine(ex.Message)

     End Try

   End Sub

 

End Class

 

 

 

Delete Data from OleDbConnection

 

Imports System

Imports System.Data

Imports System.Data.SqlClient

Imports System.Collections

Imports System.Windows.Forms

Imports System.Resources

 

Public Class MainClass

   Shared Dim OleDbConnection As System.Data.OleDb.OleDbConnection

   Shared Dim AddressBookDataAdapter As System.Data.OleDb.OleDbDataAdapter

 

   Shared Sub Main()

      Connect()

      Display()

      

      Dim ID As String = "1"

 

 

      Dim OleDbUpdateCommand As System.Data.OleDb.OleDbCommand

      OleDbUpdateCommand = new System.Data.OleDb.OleDbCommand

      

      OleDbUpdateCommand.CommandText = _

              "Delete from Employee WHERE id=" & ID & " ;  "

      OleDbUpdateCommand.Connection = OleDbConnection

 

      AddressBookDataAdapter.UpdateCommand = OleDbUpdateCommand

 

 

      AddressBookDataAdapter.UpdateCommand.ExecuteNonQuery()

 

 

      Display()

      Disconnect()

   End Sub

 

   Shared Sub Display()

      Dim OleDbSelectCommand As System.Data.OleDb.OleDbCommand

      OleDbSelectCommand = New System.Data.OleDb.OleDbCommand()

 

      OleDbSelectCommand.CommandText = "SELECT ID, FirstName, LastName,Salary FROM Employee"

      OleDbSelectCommand.Connection = OleDbConnection

 

      AddressBookDataAdapter = New System.Data.OleDb.OleDbDataAdapter()

 

      AddressBookDataAdapter.SelectCommand = OleDbSelectCommand

 

 

      Dim AddressBookDataSet As System.Data.DataSet

      AddressBookDataSet = New System.Data.DataSet()

      CType(AddressBookDataSet, System.ComponentModel.ISupportInitialize).BeginInit()

 

      AddressBookDataAdapter.Fill(AddressBookDataSet)

 

 

        Dim dataTable As DataTable = AddressBookDataSet.Tables(0)

 

        ' ensure dataTable not empty

        If dataTable.Rows.Count <> 0 Then

           Dim recordNumber As Integer = Convert.ToInt32(dataTable.Rows(0)(0))

 

           Console.Write( recordNumber.ToString & "  ")

           Console.Write( Convert.ToString(dataTable.Rows(0)(1)) & "  ")

           Console.Write( Convert.ToString(dataTable.Rows(0)(2)) & "  ")

           Console.Write( Convert.ToString(dataTable.Rows(0)(3)) & "  ")

 

           ' display not-found message

        Else

           Console.WriteLine( "No record found" )

        End If

        Console.WriteLine(  )

   End Sub

 

   Shared Sub Connect()

     OleDbConnection = New System.Data.OleDb.OleDbConnection()

 

     OleDbConnection.ConnectionString = _

        "Provider=Microsoft.Jet.OLEDB.4.0;Password="""";" & _

        "User ID=Admin;Data Source=Employee.mdb;Mode=Sha" & _

        "re Deny None;Extended Properties="""";" & _

        "Jet OLEDB:System database="""";Jet OLEDB:Regis" & _

        "try Path="""";Jet OLEDB:Database Password="""";" & _

        "Jet OLEDB:Engine Type=5;Jet OLEDB:Dat" & _

        "abase Locking Mode=1;Jet OLEDB:Global Partial " & _

        "Bulk Ops=2;Jet OLEDB:Global Bulk T" & _

        "ransactions=1;Jet OLEDB:New Database " & _

        "Password="""";Jet OLEDB:Create System Databas" & _

        "e=False;Jet OLEDB:Encrypt Database=False;" & _

        "Jet OLEDB:Don't Copy Locale on Compact=" & _

        "False;Jet OLEDB:Compact Without Replica " & _

        "Repair=False;Jet OLEDB:SFP=False"

 

 

     Try

        OleDbConnection.Open()

     Catch ex As Exception

        Console.WriteLine(ex.Message)

     End Try

   End Sub

 

   Shared Sub Disconnect()

     Try

        OleDbConnection.Close()

     Catch ex As Exception

        Console.WriteLine(ex.Message)

     End Try

   End Sub

 

End Class

 

 

Update Access data table through OleDbConnection

 

Imports System

Imports System.Data

Imports System.Data.SqlClient

Imports System.Collections

Imports System.Windows.Forms

Imports System.Resources

 

Public Class MainClass

Shared Dim OleDbConnection As System.Data.OleDb.OleDbConnection

Shared Dim AddressBookDataAdapter As System.Data.OleDb.OleDbDataAdapter

 

Shared Sub Main()

Connect()

Display()

 

Dim FirstName As String = "New Name"

Dim ID As String = "1"

 

 

 

Dim OleDbUpdateCommand As System.Data.OleDb.OleDbCommand

OleDbUpdateCommand = new System.Data.OleDb.OleDbCommand

 

OleDbUpdateCommand.CommandText = _

"UPDATE Employee SET firstName=" & _

"'" & FirstName & _

"' WHERE id=" & ID & " ; "

OleDbUpdateCommand.Connection = OleDbConnection

 

AddressBookDataAdapter.UpdateCommand = OleDbUpdateCommand

 

 

AddressBookDataAdapter.UpdateCommand.ExecuteNonQuery()

 

 

Display()

Disconnect()

End Sub

 

Shared Sub Display()

Dim OleDbSelectCommand As System.Data.OleDb.OleDbCommand

OleDbSelectCommand = New System.Data.OleDb.OleDbCommand()

 

OleDbSelectCommand.CommandText = "SELECT ID, FirstName, LastName,Salary FROM Employee"

OleDbSelectCommand.Connection = OleDbConnection

 

AddressBookDataAdapter = New System.Data.OleDb.OleDbDataAdapter()

 

AddressBookDataAdapter.SelectCommand = OleDbSelectCommand

 

 

Dim AddressBookDataSet As System.Data.DataSet

AddressBookDataSet = New System.Data.DataSet()

CType(AddressBookDataSet, System.ComponentModel.ISupportInitialize).BeginInit()

 

AddressBookDataAdapter.Fill(AddressBookDataSet)

 

 

Dim dataTable As DataTable = AddressBookDataSet.Tables(0)

 

' ensure dataTable not empty

If dataTable.Rows.Count <> 0 Then

Dim recordNumber As Integer = Convert.ToInt32(dataTable.Rows(0)(0))

 

Console.Write( recordNumber.ToString & " ")

Console.Write( Convert.ToString(dataTable.Rows(0)(1)) & " ")

Console.Write( Convert.ToString(dataTable.Rows(0)(2)) & " ")

Console.Write( Convert.ToString(dataTable.Rows(0)(3)) & " ")

 

' display not-found message

Else

Console.WriteLine( "No record found" )

End If

Console.WriteLine( )

End Sub

 

Shared Sub Connect()

OleDbConnection = New System.Data.OleDb.OleDbConnection()

 

OleDbConnection.ConnectionString = _

"Provider=Microsoft.Jet.OLEDB.4.0;Password="""";" & _

"User ID=Admin;Data Source=Employee.mdb;Mode=Sha" & _

"re Deny None;Extended Properties="""";" & _

"Jet OLEDB:System database="""";Jet OLEDB:Regis" & _

"try Path="""";Jet OLEDB:Database Password="""";" & _

"Jet OLEDB:Engine Type=5;Jet OLEDB:Dat" & _

"abase Locking Mode=1;Jet OLEDB:Global Partial " & _

"Bulk Ops=2;Jet OLEDB:Global Bulk T" & _

"ransactions=1;Jet OLEDB:New Database " & _

"Password="""";Jet OLEDB:Create System Databas" & _

"e=False;Jet OLEDB:Encrypt Database=False;" & _

"Jet OLEDB:Don't Copy Locale on Compact=" & _

"False;Jet OLEDB:Compact Without Replica " & _

"Repair=False;Jet OLEDB:SFP=False"

 

 

Try

OleDbConnection.Open()

Catch ex As Exception

Console.WriteLine(ex.Message)

End Try

End Sub

 

Shared Sub Disconnect()

Try

OleDbConnection.Close()

Catch ex As Exception

Console.WriteLine(ex.Message)

End Try

End Sub

 

End Class

 

 

Read data from Access data table

 

Imports System

Imports System.Data

Imports System.Data.SqlClient

Imports System.Collections

Imports System.Windows.Forms

Imports System.Resources

 

Public Class MainClass

   Shared Dim OleDbConnection As System.Data.OleDb.OleDbConnection

 

   Shared Sub Main()

      Connect()

      Dim OleDbSelectCommand As System.Data.OleDb.OleDbCommand

      OleDbSelectCommand = New System.Data.OleDb.OleDbCommand()

 

      OleDbSelectCommand.CommandText = "SELECT ID, FirstName, LastName,Salary FROM Employee"

      OleDbSelectCommand.Connection = OleDbConnection

 

      Dim AddressBookDataAdapter As System.Data.OleDb.OleDbDataAdapter

      AddressBookDataAdapter = New System.Data.OleDb.OleDbDataAdapter()

 

      AddressBookDataAdapter.SelectCommand = OleDbSelectCommand

 

 

      Dim AddressBookDataSet As System.Data.DataSet

      AddressBookDataSet = New System.Data.DataSet()

      CType(AddressBookDataSet, System.ComponentModel.ISupportInitialize).EndInit()

 

      AddressBookDataAdapter.Fill(AddressBookDataSet)

 

 

        Dim dataTable As DataTable = AddressBookDataSet.Tables(0)

 

        ' ensure dataTable not empty

        If dataTable.Rows.Count <> 0 Then

           Dim recordNumber As Integer = Convert.ToInt32(dataTable.Rows(0)(0))

 

           Console.WriteLine( recordNumber.ToString )

           Console.WriteLine( Convert.ToString(dataTable.Rows(0)(1)) )

           Console.WriteLine( Convert.ToString(dataTable.Rows(0)(2)) )

           Console.WriteLine( Convert.ToString(dataTable.Rows(0)(3)) )

 

           ' display not-found message

        Else

           Console.WriteLine( "No record found" )

        End If

 

 

   End Sub

 

   Shared Sub Connect()

     OleDbConnection = New System.Data.OleDb.OleDbConnection()

 

     OleDbConnection.ConnectionString = _

        "Provider=Microsoft.Jet.OLEDB.4.0;Password="""";" & _

        "User ID=Admin;Data Source=Employee.mdb;Mode=Sha" & _

        "re Deny None;Extended Properties="""";" & _

        "Jet OLEDB:System database="""";Jet OLEDB:Regis" & _

        "try Path="""";Jet OLEDB:Database Password="""";" & _

        "Jet OLEDB:Engine Type=5;Jet OLEDB:Dat" & _

        "abase Locking Mode=1;Jet OLEDB:Global Partial " & _

        "Bulk Ops=2;Jet OLEDB:Global Bulk T" & _

        "ransactions=1;Jet OLEDB:New Database " & _

        "Password="""";Jet OLEDB:Create System Databas" & _

        "e=False;Jet OLEDB:Encrypt Database=False;" & _

        "Jet OLEDB:Don't Copy Locale on Compact=" & _

        "False;Jet OLEDB:Compact Without Replica " & _

        "Repair=False;Jet OLEDB:SFP=False"

 

 

     Try

        OleDbConnection.Open()

     Catch ex As Exception

        Console.WriteLine(ex.Message)

     End Try

   End Sub

 

   Shared Sub Disconnect()

     Try

        OleDbConnection.Close()

     Catch ex As Exception

        Console.WriteLine(ex.Message)

     End Try

   End Sub

 

End Class

 

 

Dette er jo hardcore kodet koder :!: Men alle sammen bruker OleDBConnection noe jeg ikke bruker! Hva kan jeg gjøre for og endre på det til MySQL database som jeg bruker?

Endret av Gjest
Lenke til kommentar

Én ting som er litt feil med alle kodene du finner, er at de burde bruke IDbConnection, IDbDataAdapter osv. fremfor å eksplistt bruke OleDbConnection og lignende. Fordelen med å bruke interfaces istedet er at det er kjempelett å bytte data provider uten å måttte skrive om hele programmet.

Lenke til kommentar

Opprett en konto eller logg inn for å kommentere

Du må være et medlem for å kunne skrive en kommentar

Opprett konto

Det er enkelt å melde seg inn for å starte en ny konto!

Start en konto

Logg inn

Har du allerede en konto? Logg inn her.

Logg inn nå
×
×
  • Opprett ny...