Buchempfehlung
Visual Basic 6 Kochbuch
Visual Basic 6 Kochbuch
Viele praktische Tipps zum Programmieren mit Visual Basic 6, die sich oft auch auf FB übertragen lassen. [Mehr Infos...]
FreeBASIC-Chat
Es sind Benutzer im FreeBASIC-Chat online.
(Stand:  )
FreeBASIC bei Twitter
Twitter FreeBASIC-Nachrichten jetzt auch über Twitter erhalten. Follow us!

Code-Beispiel

Code-Beispiele » Datenbanken

Von FreeBASIC aus auf MySQL zugreifen

Lizenz:Erster Autor:Letzte Bearbeitung:
k. A.RedakteurMOD 24.10.2018

English description see below

Hinweis: Der Text und der Code sind Teil der Reihe Externer Link!Programmieren für Oma und wurden minimal für die Veröffentlichung hier angepasst. Vielen Dank für die Erlaubnis der Nutzung an croco97, dem Autor des Externer Link!Originaltextes.

Die Möglichkeiten mit MySQL werden natürlich erst dann richtig ausgefahren, wenn wir die Mächtigkeit einer nativen Programmiersprache wie FreeBASIC mit einem Relationales Datenbank-Management-System, kurz "RDBMS" und SQL verbinden. Let's start.

Als aller erstes müssen wir dafür sorgen, dass FreeBASIC die libmysql.dll findet. Sie findet sich nach der MySQL-Installation im MySQL-Programmverzeichnis unter lib (oder lib/opt). Aber da findet sie FreeBASIC nicht. Einfach nach windows\system32 kopieren.

Mit Freebasic SQL's abschicken und das Ergebnis lesen
Nun zur Interaktion mit FreeBASIC selbst, d.h. zu den notwendigen Befehlen der MySQL-API, um einen SQL abzuschicken und das Ergebnis nach FreeBASIC zu bekommen.


BefehlBedeutung
db = mysql_init( NULL ) Initialisiere den API-Zugriff. db ist vom Typ MYSQL Ptr und ein Handle auf das verwendete DB-System.
result = mysql_real_connect( db, NULL, "root", "a", dbname, MYSQL_PORT, NULL, 0 )Verbindet mit einer Datenbank dbname unter dem User "root", dem Passwort "a". Das zweite Argument wäre eigentlich die Adresse, (z.B. eine IP-Adresse), wo das Programm das RDBMS findet. Bei NULL sucht es auf dem eigenen Rechner (unter "localhost"). result ist vom Typ Integer und ist ungleich Null, wenn alles geklappt hat.
result = mysql_select_db( db, dbname )Auswahl der Datenbank. (Entspricht "use dbname;" innerhalb des MYSQL-Clients).
error = mysql_query( db, sql_query_string )Absetzen eines SQL-Befehls. error ist vom Typ Integer. Ist error = 0, ist alles in Ordnung. sql_query_string kann eine String-Konstante sein, also z.B. "select * from jettype;" oder eine ZString-Variable.
restab = mysql_store_result( db )Veranlasst die API, das Ergebnis der letzten Query in einer Struktur vom Typ MYSQL_RES Ptr abzuspeichern.
nrow = mysql_num_rows( restab )Die Frage ist, wie lang die Ergebnistabelle denn geworden ist. mysql_num_rows( restab ) gibt Antwort darauf. nrow ist vom Typ Integer. Tabellen > 2 Mrd. Zeilen sind tunlichst zu vermeiden...
ncol = mysql_num_fields( restab )Meistens werden wir wissen, wie viele Spalten unsere Tabelle hat. Aber sicher ist sicher. ncol ist vom Typ Integer.
row = mysql_fetch_row( restab ) Hier bekommen wir nun endlich die Daten der nächsten Zeile. row[] ist ein Array von ZStrings, also vom Typ ZString Ptr Ptr
mysql_free_result( restab )Gibt alle Resourcen der Ergebnistabelle frei.
mysql_close( db )Schliesst den RDBMS-Zugriff.

Das Ganze können wir in einem zusammenfassenden kleinen Beispielprogramm betrachten, in dem wir den Inhalt der jettype-Tabelle (näheres dazu im Externer Link!Originaltextes) auf dem Bildschirm ausgeben:

#Include Once "mysql\mysql.bi"

#Define NULL 0

Sub connect1

    Dim db As MYSQL Ptr

    'Initialisiere die API. db zeigt auf das MySQL-System.
    'Initialize the API. db points to the MySQL system.
    db = mysql_init( NULL )

    Dim dbname As String

    dbname = "test"

    'Verbinde dich mit dem MySQL-System.
    '2. Argument: Adresse des Servers. NULL = Localhost.
    'Connect to the MySQL system.
    '2nd parameter: Address of the servers. NULL = localhost.
    If( mysql_real_connect( db, NULL, "root", "a", dbname, MYSQL_PORT, NULL, 0 ) = 0 ) Then
            Print "Can't connect to the mysql server on port"; MYSQL_PORT
            mysql_close( db )
            End 1
    End If

    'Waehle die Datenbank aus.
    'Select a data base.
    If( mysql_select_db( db, dbname ) ) Then
                Print "Can't select the "; dbname; "Color = teal>"" database !"
                mysql_close( db )
                End 1
    End If

    'Gib ein Informationen zum RDBMS-Host und zur Datenbank aus.
    'Print informations about the RDBMS host and the data base.
    Print "Client info: "; *mysql_get_client_info( )
    Print "Host info: "; *mysql_get_host_info( db )
    Print "Server info: "; *mysql_get_server_info( db )

    'Schicke eine SQL Abfrage los.
    'Submit a SQL query.
    Dim res As Integer
    res = mysql_query( db, "select * from jettype;" )

    'Deklariere einen Zeiger auf die Ergebnistabelle
    'Declare a pointer to the result table
    Dim restab As mysql_res Ptr

    If res = 0 Then
        'Hole den Zeiger auf die Ergebnistabelle
        'Get the pointer to the result table
        restab = mysql_store_result( db )
        If restab > 0 Then
            Dim As Integer nrow
            'Wie viel Zeilen hat die Ergebnistabelle?
            'How many rows are in the result table?
            nrow = mysql_num_rows( restab )
            Print nrow
            If nrow > 0 Then

                Dim As Integer i, j, ncol
                Dim As mysql_row row
                'Wie viel Spalten hat die Ergebnistabelle?
                'How many columns are in the result table?
                ncol = mysql_num_fields( restab )

                Print ncol
                'Lies die Ergebnistabelle aus.
                'Read the result table.
                For i = 0 To nrow - 1
                    'Hole die naechste Zeile der Ergebnistabelle
                    'Get the next row of the result table
                    row = mysql_fetch_row( restab )
                    Print i,
                    'Gib alle Spalten der aktuellen Zeile auf dem Bildschirm aus.
                    'Print all columns of the current row to the screen.
                    For j = 0 To ncol - 1
                        Dim s As String: s = *row[j]
                        Print s; " - ";
                    Next j
                    Print
                Next i
                Sleep
            End If
        End If
        'Mache den Speicherplatz der Ergebnistabelle frei.
        'Release the memory of the result table.
        mysql_free_result( restab )
    Else
        Print "sql query error"
    End If
    'Schliesse den API-Zugang.
    'Close the API access.
    mysql_close( db )
    End 0

End Sub

connect1

Bei Interesse des Themas Datenbanken mit MySQL und FreeBASIC sollte das vollständige Externer Link!Tutorial gelesen werden. Darin werden die Grundlagen von Datenbanken besprochen, ein kleiner Einblick in den Funktionsumfang gegeben und es bietet ein vollständiges Beispiel mit Übungsaufgaben, die den Lernerfolg weiter fördern.

English:

Hint: The text and the code are part of the series Externer Link!Programmieren für Oma ("programming for grandma") and were slightly customized for this publication. Many thanks for the permission of using it to croco97, the author of the Externer Link!original text.

Of course there's only made full use of the features provided by MySQL, when we combine the power of a native programming language like freeBASIC with a relational database management system, abbreviated "RDBMS", and SQL. Let's start.

The very first thing we have to do is making sure that FreeBASIC finds the libmysql.dll. After the installaton of MySQL it can be found in the lib (or lib/opt) subfolder of the MySQL directory. But there it can't be found by FreeBASIC. Simply copy it to windows\system32.

Send SQLs with FreeBASIC and read the result
Now let's turn to the interaction with FreeBASIC itself, i.e. to the required commands of the MySQL-API, to send an SQL and get the result to FreeBASIC.

CommandMeaning
db = mysql_init( NULL ) Initialize the API-access, db is of the Type MYSQL Ptr and a handle to the applied DB-system.
result = mysql_real_connect( db, NULL, "root", "a", dbname, MYSQL_PORT, NULL, 0 )Connects to a data base dbname with the user "root" and the password "a". The 2nd parameter determines the address (e.g. an IP address), where the program can find the RDBMS. If set to NULL it seeks on the own computer (under "localhost"). Result is of the Type Integer and nonzero if the function succeeds.
result = mysql_select_db( db, dbname )Selection of the data base. (Is equivalent to "use dbname;" inside of the MYSQL-client).
error = mysql_query( db, sql_query_string )Send an SQL command. error is of the Type Integer. If error = 0, everything's alright. sql_query_string may be a string constant, e.g. "select * from jettype;", or a ZString variable.
restab = mysql_store_result( db )Instructs the API to store the result of the last query to a structure of the Type MYSQL_RES Ptr.
nrow = mysql_num_rows( restab )Answers the question, how long the result table has become. nrow is of the Type Integer. Tables > 2 millard rows are to be avoided at any cost...
ncol = mysql_num_fields( restab )Usually we will know of how much columns our table consists. But just to make sure. ncol is of the Type Integer.
row = mysql_fetch_row( restab ) Finally we get the data of the next row. row[] is an array of ZStrings, therefore of the Type ZString Ptr Ptr
mysql_free_result( restab )Releases all resources of the result table.
mysql_close( db )Closes the RDBMS-access.

We can view that all in a summarizing little example program that prints the contents of the jettype-table (particulars in the Externer Link!original text) to the screen:

(Source code see above)

If you're interested in the theme databases with MySQL and FreeBASIC the complete Externer Link!Tutorial should be read. Therein the basics of databases are discussed, it's given a little insight into the function range, and it provides a complete example with exercises to promote the learning success.


Zusätzliche Informationen und Funktionen
  • Das Code-Beispiel wurde am 09.08.2011 von RedakteurMOD angelegt.
  • Die aktuellste Version wurde am 24.10.2018 von Mitgliedgrindstone gespeichert.
  Bearbeiten Bearbeiten  

  Versionen Versionen