MySQL Client Server

download MySQL Client Server

of 439

Transcript of MySQL Client Server

  • 7/31/2019 MySQL Client Server


  • 7/31/2019 MySQL Client Server


  • 7/31/2019 MySQL Client Server


  • 7/31/2019 MySQL Client Server


  • 7/31/2019 MySQL Client Server


  • 7/31/2019 MySQL Client Server


  • 7/31/2019 MySQL Client Server


  • 7/31/2019 MySQL Client Server


  • 7/31/2019 MySQL Client Server


  • 7/31/2019 MySQL Client Server


  • 7/31/2019 MySQL Client Server


  • 7/31/2019 MySQL Client Server


  • 7/31/2019 MySQL Client Server


  • 7/31/2019 MySQL Client Server


  • 7/31/2019 MySQL Client Server


  • 7/31/2019 MySQL Client Server


  • 7/31/2019 MySQL Client Server


  • 7/31/2019 MySQL Client Server


  • 7/31/2019 MySQL Client Server


  • 7/31/2019 MySQL Client Server


  • 7/31/2019 MySQL Client Server


  • 7/31/2019 MySQL Client Server


  • 7/31/2019 MySQL Client Server


  • 7/31/2019 MySQL Client Server


  • 7/31/2019 MySQL Client Server


  • 7/31/2019 MySQL Client Server


  • 7/31/2019 MySQL Client Server


  • 7/31/2019 MySQL Client Server


  • 7/31/2019 MySQL Client Server


  • 7/31/2019 MySQL Client Server


  • 7/31/2019 MySQL Client Server


  • 7/31/2019 MySQL Client Server


  • 7/31/2019 MySQL Client Server


  • 7/31/2019 MySQL Client Server


  • 7/31/2019 MySQL Client Server


  • 7/31/2019 MySQL Client Server


  • 7/31/2019 MySQL Client Server


  • 7/31/2019 MySQL Client Server


  • 7/31/2019 MySQL Client Server


  • 7/31/2019 MySQL Client Server


  • 7/31/2019 MySQL Client Server


  • 7/31/2019 MySQL Client Server


  • 7/31/2019 MySQL Client Server


  • 7/31/2019 MySQL Client Server


  • 7/31/2019 MySQL Client Server


  • 7/31/2019 MySQL Client Server


  • 7/31/2019 MySQL Client Server


  • 7/31/2019 MySQL Client Server


  • 7/31/2019 MySQL Client Server


  • 7/31/2019 MySQL Client Server


  • 7/31/2019 MySQL Client Server


  • 7/31/2019 MySQL Client Server


  • 7/31/2019 MySQL Client Server


  • 7/31/2019 MySQL Client Server


  • 7/31/2019 MySQL Client Server


  • 7/31/2019 MySQL Client Server


  • 7/31/2019 MySQL Client Server


  • 7/31/2019 MySQL Client Server


  • 7/31/2019 MySQL Client Server


  • 7/31/2019 MySQL Client Server


  • 7/31/2019 MySQL Client Server


  • 7/31/2019 MySQL Client Server


  • 7/31/2019 MySQL Client Server


  • 7/31/2019 MySQL Client Server


  • 7/31/2019 MySQL Client Server


  • 7/31/2019 MySQL Client Server


  • 7/31/2019 MySQL Client Server


  • 7/31/2019 MySQL Client Server


  • 7/31/2019 MySQL Client Server


  • 7/31/2019 MySQL Client Server


  • 7/31/2019 MySQL Client Server


  • 7/31/2019 MySQL Client Server


  • 7/31/2019 MySQL Client Server


  • 7/31/2019 MySQL Client Server


  • 7/31/2019 MySQL Client Server


  • 7/31/2019 MySQL Client Server


  • 7/31/2019 MySQL Client Server


  • 7/31/2019 MySQL Client Server


  • 7/31/2019 MySQL Client Server


  • 7/31/2019 MySQL Client Server


  • 7/31/2019 MySQL Client Server


  • 7/31/2019 MySQL Client Server


  • 7/31/2019 MySQL Client Server


  • 7/31/2019 MySQL Client Server


  • 7/31/2019 MySQL Client Server


  • 7/31/2019 MySQL Client Server


  • 7/31/2019 MySQL Client Server


  • 7/31/2019 MySQL Client Server


  • 7/31/2019 MySQL Client Server


  • 7/31/2019 MySQL Client Server


  • 7/31/2019 MySQL Client Server


  • 7/31/2019 MySQL Client Server


  • 7/31/2019 MySQL Client Server


  • 7/31/2019 MySQL Client Server


  • 7/31/2019 MySQL Client Server


  • 7/31/2019 MySQL Client Server


  • 7/31/2019 MySQL Client Server


  • 7/31/2019 MySQL Client Server


  • 7/31/2019 MySQL Client Server


  • 7/31/2019 MySQL Client Server


  • 7/31/2019 MySQL Client Server


  • 7/31/2019 MySQL Client Server


  • 7/31/2019 MySQL Client Server


  • 7/31/2019 MySQL Client Server


  • 7/31/2019 MySQL Client Server


  • 7/31/2019 MySQL Client Server


  • 7/31/2019 MySQL Client Server


  • 7/31/2019 MySQL Client Server


  • 7/31/2019 MySQL Client Server


  • 7/31/2019 MySQL Client Server


  • 7/31/2019 MySQL Client Server


  • 7/31/2019 MySQL Client Server


  • 7/31/2019 MySQL Client Server


  • 7/31/2019 MySQL Client Server


    Chapter 5: Configuration of Users and Hosts 89

    You can find out what users exist and whether passwords, if any, exist for those users,with a SQL SELECT statement, like so:

    [whil@example ~] mysql -u root -p mysql> select host, user, password from mysql.user ;

    +------------------+------+------------------+| host | user | password |+------------------+------+------------------+| localhost | root | 48bf4fd20c61a2f0 || example | root | 48bf4fd20c61a2f0 || localhost | | || example | | |+------------------+------+------------------+4 rows in set (0.07 sec)

    This shows that the MySQL user, root, has had a password assigned, but the anonymoususer has none. The password shown, 48bf4fd20c61a2f0, by the way, isnt the real rootpassword, but the hashed version, due to the use of the password function in the setpassword command.

    Youll want to set passwords for both the localhost and real name domains, both for rootand the anonymous user. The following commands use the word secret for the password forall four user/host combinations:

    mysql> set password for ''@'localhost' = password('secret'); mysql> set password for ''@'example' = password('secret'); mysql> set password for 'root'@'localhost' = password('secret'); mysql> set password for 'root'@'example' = password('secret');

    Id suggest you dont actually use the word secret as your password, though.

    This information is covered, with a lot of additional examples, in section 2.9.3, Securingthe Initial MySQL Accounts. Definitely worth checking out!

    How MySQL user passwords affect commandsI want to briefly mention that you need to include the -u and -p flags when runningMySQL scripts. Now that your feet are wet with users, passwords, and hosts, its probably agood time to revisit this concept.

    After you assign a password to the root mysql user, youll need to prompt for a passwordwith the -p clause as well, like so:

    [whil@example ~] /usr/bin/mysqladmin -u root -p shutdownEnter password:[whil@example ~] 040731 16:57:24 mysqld ended

    Or else youll get an error like so:

    [whil@example ~] /usr/bin/mysqladmin -u root shutdown/usr/bin/mysqladmin: connect to server at 'localhost' failederror: 'Access denied for user: 'root@localhost' (Using password: NO)'

    Another example of failure is when you try to run the MySQL monitor:

  • 7/31/2019 MySQL Client Server


    90 MySQL Client-Server Applications with Visual FoxPro

    [whil@example ~] mysql -u rootERROR 1045: Access denied for user: 'root@localhost' (Using password: NO)

    Including the -p clause results in this exchange with the computer:

    [whil@example ~] mysql -u root -pEnter password:

    Welcome to the MySQL monitor. Commands end with ; or \g.Your MySQL connection id is 11 to server version: 4.0.20-standard-log

    Type 'help;' or '\h' for help. Type '\c' to clear the buffer.


    And now youre connected to the MySQL database server via the monitor as the MySQLuser named root.

    If youre trying to connect with a MySQL server on a separate machine, you may need to

    include the -h flag, like so:[whil@example ~] mysql -h some_host -u root -p

    or like so:

    [whil@example ~] mysql -h - u root -p

    If your local machine is set up so it can resolve some_host, you wont need the -hflag. If, however, you get the following:

    [whil@example ~] mysql another_host -u root -pEnter password: **********ERROR 1049 (42000): Unknown database 'another_host'

    you may need to explicitly identify the host to connect to via the -h flag.Note: If you install MySQL on Linux using RPM distributions, the server RPM runs the

    mysql_install_db script automatically. This script creates the mysql and test databases andsets up initial users. If you install differently (say, from source blech!), youll need to do thisyourself. See Unix Post-Install Procedures in the on-line help for step-by-step instructions.

    Adding a work-a-day userJust like you wouldnt want to use MySQL with a password-less user, you wont want toconnect to MySQL via the root user for your regular daily work. Time to create a work-a-dayuser. Remember bob?


    This will create a user named bob with the password of secret who has full privilegeson localhost.

    You can now access MySQL like so:
  • 7/31/2019 MySQL Client Server


    Chapter 5: Configuration of Users and Hosts 91

    [whil@example ~] mysql -u bob -pEnter password:


    Remember the

    mysql> select host, user, password from mysql.user ;

    command in order to look at what users (and their permissions) are in your system. Themysql.user table actually has a lot of fields in it, each of which specifies permission for aspecific action. For example, the contents of the select_priv field determines whether a givenhost/user combination can do queries, while the contents of the insert_priv field determineswhether or not a host/user combo can insert records.

    Conclusion/SummaryGetting used to accessing a back-end database takes a bit of time, but after spending an hour ortwo practicing, youll feel right at home. MySQLs user access architecture is straightforwardand easy to work with. However, if you are not a command line guru, and would rather dealwith one of the GUI interfaces for all of your administration, you are in luck. Regardless of theOS, there is both a Web interface and a GUI interface that allows you to manage users, addand grant privileges, and create a database and tables without ever seeing a command line. Itsnice to know the command line is there if you want it, but its not necessary as youre buildingyour VFP-MySQL applications. Lets move on to connecting these tools.

    Now its time to connect to MySQL from Visual FoxPro.

    Updates and corrections to this chapter can be found on Hentzenwerkes Web site, . Click Catalog and navigate to the page for this book.
  • 7/31/2019 MySQL Client Server


    92 MySQL Client-Server Applications with Visual FoxPro

  • 7/31/2019 MySQL Client Server


    Chapter 6: Connecting VFP to MySQL 93

    Chapter 6Connecting VFP to MySQL

    Now that we have MySQL server up and running with the right users and hosts, its timeto direct our attention to the Windows box running VFP. In this chapter, we will connectto MySQL from within Visual FoxPro, using the MySQL ODBC driver and a brief set ofVFP commands.

    This chapter covers two processes the installation of the ODBC driver, and the subsequentuse of the driver from within VFP to connect to the MySQL server.

    In this chapter, I use multiple screen shots of the ODBC driver installation process. In thepast, the screens have changed from one version to another, so its possible that they havechanged again since this writing. Ive found, though, during the review process, that the endresult of the ODBC installation is the same, and you shouldnt have any trouble if youre usinga later version than what is described in this text.

    After a quick stop to install the ODBC driver, well go right to the interesting stuff connecting from VFP.

    Installing the MySQL ODBC driverNow that MySQL is installed and you have confirmed that it is working, its time to addressthe next piece of the puzzle the connector between VFP and MySQL: the ODBC driver.

    Uninstalling an old version of the MySQL ODBC driverIf you need to uninstall a previous version of the MySQL ODBC driver, you can do sothrough the Add/Remove Programs applet in the Control Panel. Scroll down the list and look for MyODBC in the list of programs.

    Downloading the MySQL ODBC driverHead back to the MySQL download page and grab the MySQL ODBC driver. Click on theConnectors link in the same band as the Database Server link, and follow the sameprocedure for either the Driver Installer (Zipped EXE) or Driver Installer (MSI) link.

    Depending on which one you download (theyre functionally the same) the file will benamed something like



    Theyre both about 3 MB in size.

  • 7/31/2019 MySQL Client Server


    94 MySQL Client-Server Applications with Visual FoxPro

    Installing the MyODBC driverEither unzip the ZIP file and run the EXE file that it contains, or right-click on the MSI fileand select the Install option in the context menu.

    In both cases, the wizard will start, as shown in Figure 1 .

    Figure 1 . Starting the MySQL ODBC driver wizard.

    Continue through the next couple of dialogs, and then choose the Custom selectionshown in Figure 2 s setup type selection.

  • 7/31/2019 MySQL Client Server


    Chapter 6: Connecting VFP to MySQL 95

    Figure 2 . The set up type selection for the ODBC driver.

    I always choose Custom when doing installs so I can see what the various features are.Often I go with the defaults, but its nice to see what else might be available. This brings us tothe Custom Setup screen shown in Figure 3 .

  • 7/31/2019 MySQL Client Server


    96 MySQL Client-Server Applications with Visual FoxPro

    Figure 3 . The feature selection tree for the ODBC driver.

    In this particular situation, I keep all the features selected. Click Next to begin theinstallation, shown in Figure 4 .

  • 7/31/2019 MySQL Client Server


    Chapter 6: Connecting VFP to MySQL 97

    Figure 4 . Starting the installation of the ODBC driver.

    Youll note that there is no installation folder selection ODBC drivers are all handledthe same way so that Windows knows where to find them. The thermometer bar and progressmessages will display as expected and shown in Figure 5 .

    Figure 5 . The thermometer bar and message display during installation.

  • 7/31/2019 MySQL Client Server


    98 MySQL Client-Server Applications with Visual FoxPro

    And if all goes well, youll get the confirmation dialog as shown in Figure 6 .

    Figure 6 . The confirmation dialog for the ODBC driver.Open the ODBC Data Source Administrator. This applet is found via Start | Settings |

    Control Panel | Administrator tools | Data Sources (ODBC) in Windows 2000, and Start |Control Panel | Performance and Maintenance | Administrator Tools | Data Sources (ODBC) inWindows XP. Note that some configurations of XP do not have a Performance andMaintenance folder. Click on the Drivers tab.

    Youll see the MySQL ODBC driver in the list along with whatever other drivers areinstalled on your computer, as shown in Figure 7 .

  • 7/31/2019 MySQL Client Server


    Chapter 6: Connecting VFP to MySQL 99

    Figure 7 . The Data Source Administrator dialog now shows the MySQL driver too.

    You can use this same driver multiple times, with multiple versions of Visual FoxProand/or MySQL you dont have to install multiple copies for different purposes.

    The installation places the myodbc3.dll and myodbc3.lib files in the WinNT\system32directory.

    Connecting to MySQL from VFPWere going to test the connection from VFP to MySQL in several steps. First, well do it thewizard way by using a DSN (Data Source Name) that hides the details of the connectionfrom us. This step will help us verify that the connection works, since error messages thatspring up during the use of a DSN are easier to interpret than when testing manually.

    Next, well manually build a connection string from the DSN, and use that string to do thesame connection to VFP. Along the way, well learn the basics of issuing commands to theMySQL database server from within VFP.

    Well also look at how to use VFPs error handling capabilities to trap errors and whatthose errors mean to us in the real world.

    Connecting to MySQL from VFP with a DSNDSNs are Windows objects that contain the information necessary to make a connection to adata source. These objects are stored in the Windows Registry. There are three types: File,User, and System.

  • 7/31/2019 MySQL Client Server


    100 MySQL Client-Server Applications with Visual FoxPro

    A File DSN can be stored anywhere and used by any user who has access to theappropriate ODBC drivers. A User DSN, on the other hand, resides on the local machine andis tied to the User ID who created it.

    The third type, System, can be used by anyone who has access to the machine, and is the

    type were going to create. Then well use this DSN inside VFP.

    Creating a System DSNTo create the System DSN:

    1. On your Windows machine, open up the ODBC Administrator.2. Click System DSN tab, as shown in Figure 8 .

    Figure 8 . The System DSN tab of the Data Source Administrator allows you to create new DSNs for the box.

    3. Click the Add button.4. The Create New Data Source dialog appears as shown in Figure 9 .

  • 7/31/2019 MySQL Client Server


    Chapter 6: Connecting VFP to MySQL 101

    Figure 9 . Creating a new DSN using the MySQL ODBC driver.

    5. Select the MySQL ODBC driver.

    6. Click Finish.7. The MySQL Connector/ODBC dialog appears, as shown in Figure 10 .

  • 7/31/2019 MySQL Client Server


    102 MySQL Client-Server Applications with Visual FoxPro

    Figure 10 . Selecting the MySQL ODBC driver opens a MySQL dialog for setting parms.

    8. Enter the following settings:

    name: a unique name, such as 'mysqltest'description: enter a description for this driver if you like (it shows up inthe ODBC Admin dialog's Configuration page)server: (leave blank the driver will default to localhost, which makes sensesince the MySQL server will be on the same machine as VFP)user: bob (this is the mysql user)

    password: secret (the password for bob, the mysql user)

    If youre going to try your first connection attempt with a MySQL server running on aLinux box, youll need to enter the name of the server in the server textbox. You can enterthe name of the machine or the IP address.

    No entry for the database is necessary, since were just connecting to the MySQL server,

    but not opening a specific database. See Figure 11 for an example of what the dialog shouldlook like.

  • 7/31/2019 MySQL Client Server


    Chapter 6: Connecting VFP to MySQL 103

    Figure 11 . The ODBC Connector dialog with appropriate values filled in.

    Dont click the OK button yet we want to test the parameters first.

    Testing the system DSNWhile youre still in the ODBC dialog, its time to test the connection.

    Click the Test button. If it works, you should get a dialog indicating your good fortune,as shown in Figure 12 .

    Figure 12 . Success youve connected to the MySQL server using the DSN.

  • 7/31/2019 MySQL Client Server


    104 MySQL Client-Server Applications with Visual FoxPro

    Dealing with errorsIf you have not been quite so lucky as to have had a successful test immediately, here are acouple of troubleshooting ideas.

    The first thing that might happen is a general failure, as shown in Figure 13 .

    Figure 13 . A general failure message.

    The SQL_ERROR message isnt very helpful, so close the error dialog, and then click the Diagnostics button in the ODBC dialog where youll see diagnostic messages like thoseshown in Figure 14 .

    Figure 14 . The diagnostics panel in the ODBC configuration dialog.

  • 7/31/2019 MySQL Client Server


    Chapter 6: Connecting VFP to MySQL 105

    Upon stumbling into a message like this, you might want to do the equivalent of askingthe user if the printer is plugged in check to see if the MySQL server is running. Dontlaugh, its happened to this author once or twice.

    An alternative version of this message is

    Can't connect to MySQL server on '' (10061)

    With an IP address, this error likely means you cant reach the machine 1.11 (the machinethat the MySQL server is running on) from your Windows machine. This isnt a MySQLproblem as much as a network error, such as a firewall problem or the wrong IP address.

    Older versions of the ODBC configure dialog had a dialog that allowed you to try to pingthe 1.11 machine. In the name of progress, that dialog has been replaced by the generic errordialog shown in Figure 13, so youll have to ping the box yourself. (Open a DOS box and typeping localhost or ping and Ctrl-C to stop the ping process. Note thatWindows stops pinging after the fourth iteration while *nix does not.)

    If you cant ping the box, its likely an IP or network plumbing issue. If you can ping itbut cant reach it from the ODBC test dialog, the more likely culprit is a firewall.

    Lets take a look at what some of the other typical error messages you might see in thediagnostics pane of the ODBC configuration dialog (all errors generate the same genericfailure dialog in Figure 13.)

    Another problem you might run into is a message that says something like

    Unknown MySQL server host '' (11001)

    This error happens when the host identified in the Server text box on the Login tab of theODBC driver dialog (Figure 11) is bad. Youll need to do some sleuthing on your machine tofind out why. In this example, you can see that the host,, is obviously incorrect(as none of the octets in an IP address cant have a value > 255.)

    The next error you might encounter looks like this:

    Access denied for user 'roooot'@'localhost' (using password: YES)

    This error means that the user credentials either the username or the password (or both) that were entered in the dialog in Figure 11 are bad. Again, youll need to do someinvestigating on your own. In this example, you can see that the username root wasmisspelled.

    If you receive an error dialog that says something like

    Host '' is not allowed to connect to this MySQL server

    it means that youre successfully connecting to the machine and finding the server, but theMySQL server isnt allowing you in. Specifically, the user bob isnt allowed to access theMySQL server from the host youre connecting from (in this example, the host being192.168.1.7). You need to add a record for bob that will allow him to access the MySQLserver from the 1.7 machine.

    See the Adding a work-a-day user section in Chapter 5.

  • 7/31/2019 MySQL Client Server


    106 MySQL Client-Server Applications with Visual FoxPro

    A VFP-specific DSN optionNow that youve proved that the basic network plumbing is working, you need to make onesetting change so the DSN works with VFP. Strictly speaking, you can wait until later, but if Idont include it now, you (and I) will forget later, and then all sorts of arcane errors will start

    showing up.Click on the Advanced tab in the dialog, and check the Dont Optimize Column Widthcheck box, as shown in Figure 15 .

    Figure 15 . Setting the Dont Optimize Column Width option in the ODBC driver dialog.

    MySQL, by default, returns the real width of a column, but this action isnt looked

    upon kindly by Visual FoxPro. Specifically, you need the Dont Optimize checkboxselected for memo and integer fields. Checking this box forces MySQL to return the definedwidth, much more to VFPs liking. Specifically, two things can happen without the DontOptimize setting.

    First, with respect to views, if a field value gets truncated in a view query/requery, VFPwill return error 1494 - View definition has been changed. Second, with respect to memofields, if a MySQL query returns a character field of 255 characters or less, VFP will create acharacter field in the resultant cursor instead of a memo field. Then, if you perform any memo-specific operations on this field, youll get error 350 - Field must be a memo field.

  • 7/31/2019 MySQL Client Server


    Chapter 6: Connecting VFP to MySQL 107

    You may also want to check the Pad CHAR field to full length option on the Flags 2tab, which forces the MySQL server to fill out its varchar fields to the maximum lengthspecified. If you dont do this, some of your queries may return erratic results.

    Once you select the Dont Optimize check box (and any others), click the OK button.

    Now its time to go to the next section where you use the DSN to connect to the MySQLserver from within Visual FoxPro.

    Use the DSN on the Windows machine to connect from VFPNow that the connection via the DSN is working, well use the DSN to connect fromwithin VFP.

    Open Visual FoxPro, and enter

    ? sqlconnect("mysqltest")

    in the Command Window, where mysqltest is the name of the System DSN you created

    in Figure 11. You should get a response back in the VFP desktop that simply says 1, asshown in Figure 16 .

    Figure 16 . A successful SQLCONNECT command returns a value of 1.If you have already created a connection, you will get a value other than 1. For example,

    if you execute SQLCONNECT three times, you should get return values of 1, 2, and 3. Theserepresent three separate handles to the three connections you just created.

    How to disconnectWhen youre ready to close the connection, you issue the sqldisconnect() function, passing thevalue of the handle that was returned by the sqlconnect() function a moment earlier, like so:

    ? sqldisconnect(1)

    Obviously, youre not going to pass hard-coded values of connection handles in yourapplications. Instead, youll assign the return value from the sqlconnect() function to a variableor property, and then pass that variable/property to sqldisconnect() as the parameter:

    m.liHandle = sqlconnect("mysqltest")

    m.liSuccess = sqldisconnect(m.liHandle)

  • 7/31/2019 MySQL Client Server


    108 MySQL Client-Server Applications with Visual FoxPro

    And m.liSuccess will either be a positive integer if the command worked, or negative if it failed.

    Closing all connections

    You can also pass a parameter of zero to close all open connections:

    ? sqldisconnect(0)

    Success, again, is indicated with a return value of 1.By the way, exiting Visual FoxPro also closes all open connections automatically, as you

    probably already guessed.

    When to use (iHandle) and when to use (0)In some cases, it is safer to use the SQLDISCONNECT(0) option. If you instantiate an object,do some work, and then exit I would recommend using the global disconnect option (passing a

    parm of 0). Why? Well, Internet based systems arent like networked systems where you cancreate a connection and then create and release connection handles at will. The connectionneeds to be created and released as well as the handles in an Internet-based environment.

    For example, there have been instances using VFP 7 in Internet applications where a file-based PRG closed the connection via file handles, not using the SQLDISCONNECT(0)option. Unfortunately, the connections all piled up and became an operational issue. If yoursystem is on a network, you can use the specific handle number, but if youre accessing dataover the Internet and creating a connection as a result of a web page hit, use the globaldisconnect option. With an Internet application, where you cant be sure of what type of userload youll encounter, it always pays to be as frugal with connections as possible.

    Connecting to MySQL from VFP with a connection stringNow, well build a manual connection string from the DSN created in the last section, and usethat string to do the same connection to VFP. Along the way, well learn the basics of issuingcommands to the MySQL database server from within VFP.

    Creating a connection string to connect from VFPThe magical question has always been How do you determine what the syntax of aconnection string is? You could make random guesses, of course, or, if you had a millionmonkeys and a million typewriters, you could have them do it for you.

    But the easy answer is to use VFP to grab the parameters from an existing connection thatyou already know works. Heres an example.

    m.liHandle = sqlconnect("mysqltest") m.lcX = sqlgetprop(m.liHandle, "ConnectString")

    ? strtofile(m.lcX, "\teststring.txt")

    The first line creates a connection, and assigns the connection handle to a variable thatyoull use in the next line. The second line grabs the connection string from the connection viathe SQLGetProp function. It passes the handle of the connection you want the string for andthe property youre interested in (ConnectString) and stores the result the connectionstring to a variable.

  • 7/31/2019 MySQL Client Server


  • 7/31/2019 MySQL Client Server


    110 MySQL Client-Server Applications with Visual FoxPro

    A key-value pair looks like


    while multiple key-value pairs are strung together like so:SERVER=localhost;UID=bob;PWD=secret

    The use of the semi-colon can be especially confusing to VFP developers since it is beingused as a parameter separator, not as a line-continuation character as we are accustomed to.That means if you end up with a connection string that spans multiple lines, youll want to bedoubly careful about where you put the key-value pairs and their semi-colons. There doesnthave to be a semi-colon after the last key-value pair anymore than youd include a commaafter the last item in a list.

    Additional connection string optionsDepending on how you set up your connection information (say, suppose you entered adescription in the dialog in Figure 11), you might have already found additional strings in yourconnection string. The following contains an entry for the server localhost in this case.

    "DRIVER={MySQL ODBC 3.51 Driver};SERVER=localhost;UID=bob;PWD=secret"

    And this connection string has a string for the Dont optimize column width setting inthe Advanced tab of the ODBC dialog.

    "DRIVER={MySQL ODBC 3.51 Driver};OPTION=1;UID=bob;PWD=secret"

    The sudden appearance of more and more parameters in the connection string can soonlead one to think that youll never learn all of the possible values, and that you better just stick to the DSN wizard. Not necessarily! Putting together a complete list is straightforward, onceyou learn the tricks.

    So far youve seen the key-value pairs for most of the controls in the Login tab of theODBC dialog. To round out the list, here is the complete set of key-value pairs for theLogin tab:

    DRIVER={MySQL ODBC 3.51 Driver}DESCRIPTION=A helpful phrase about the connectionSERVER=localhostUID=bobPWD=secretDATABASE=test

    The DATABASE parameter is useful if youre setting up a connection to a knowndatabase. In some applications, you may be accessing more than one database, and will switchbetween them using the same connection, so you wouldnt need to specify the database here.

    The Connect Options tab of the ODBC dialog, shown in Figure 17 , also has associatedkey-value pairs that can be put into a connection string.

  • 7/31/2019 MySQL Client Server


    Chapter 6: Connecting VFP to MySQL 111

    Figure 17 . The Connect Options tab of the ODBC dialog allows you to specify non- standard port and socket connection information.

    The PORT parameter explicitly identifies the port that youre connecting to the MySQLserver on. If you dont include it, the connection assumes the default 3306. Some reviewers of this book have noted that theyve had to use non-standard ports for their MySQL installation,like so:


    The Socket parameter (shown in Figure 17) is only used if you are connecting to theMySQL server named localhost. The value here is the name of the Unix socket file orWindows named pipe. The Initial Statement is a command to execute when connecting toMySQL. Both of these are beyond the realm of this book.

    If youve already opened up the Advanced tab of the ODBC configuration dialog, youmay be concerned about the two dozen or so choices in the various FlagN tabs. Do I really

    need to learn and specify two dozen more parameters in my connection string? yourethinking.The answer is no. Instead, you assign a binary combination of flags that represent each

    option to the OPTION parameter, like so:


    The 22 choices in the Advanced tab each have a numeric value assigned to them. Eachvalue is a different power of two, so you can uniquely identify any combination of choiceswith a single value. For example, the Dont optimize column width option has a value of 1,

  • 7/31/2019 MySQL Client Server


    112 MySQL Client-Server Applications with Visual FoxPro

    the Return matching rows option has a value of 2, and the Safe option has a value of 131,072. If you wanted to create a connection string that included all three of these options,youd add 1+2+131072 (which totals 131,075), and then include a key-value pair of


    in your connection string. The values for each choice in the Advanced tab are listed insection Connection Parameters of the on-line help.

    Stringing a bunch of parameters together can lead to a rather long connection string,like so:

    ? sqlstringconnect("DRIVER={MySQL ODBC 3.51Driver};SERVER=;PORT=3307;OPTION=3;UID=


    When you decide to break this string onto multiple lines, dont forget the beginning andending double quotes that delineate the entire connection string, and to take care of the semi-colons that separate each parameter. The truly particular might do it something like this:

    ? sqlstringconnect("DRIVER={MySQL ODBC 3.51 Driver};" ;+ "SERVER=;" ;+ "PORT=3307;" ;+ "OPTION=3;" ;+ "UID= bob;" ;+ "PWD=secret;" ;+ "database=test")

    Of course, your mileage may vary.

    Dealing with errors programmaticallyYour first hint that something is amiss is that you dont get an immediate response; typically, asuccessful connection returns a value before you can blink. A connection attempt that fails cantake 5 to 10 seconds before the dreaded -1 appears.

    If youve mistyped the connection string, like so:

    m.lcXN = "{DRIVER=MySQL ODBC 3.51 Driver};SERVER=;UID= bob;PWD=secret;"

    (the error is that the opening braces is before the word DRIVER instead of before theword MySQL, which is a common problem), youll get a dialog box asking you where thedriver is, as shown in Figure 18 .

  • 7/31/2019 MySQL Client Server


    Chapter 6: Connecting VFP to MySQL 113

    Figure 18 . The Select Data Source dialog appears if you mistype a driver name.

    Other times, errors can be more obscure. Error information can be captured via theAERROR function, like so:

    ? sqlstringconnect("DRIVER={MySQL ODBC 3.51 Driver};" ;+ "SERVER=192.999.999.999;" ;+ "UID= bob;" ;+ "PWD=secret;)

    dimension abc[1]? aerror(abc)

    (Youll notice that the IP address for the server is invalid, thus generating an error.) Openup your Locals window (found under the Tools menu if the Debugger is in the FoxPro frameor under the VFP Debuggers Window menu if youre running the debugger in its own frame)as shown in Figure 19

    Figure 19 . The Locals window allows you to easily drill down into an AERROR array.

  • 7/31/2019 MySQL Client Server


    114 MySQL Client-Server Applications with Visual FoxPro

    and spelunk through the results. Unfortunately, the errors returned by the driver can be verymisleading. In this example, I specified a bad server name, which means the driver wasntgoing to be able to find the server. The error returned, Could not find driver..., doesnt makesense the error should have been something like Could not find server.

    If you dont want to go through the trouble of using the Locals window, you can simplyissue a

    display memory like abc

    command and view the results on the VFP desktop.And now back to our regularly scheduled program.

    DSNs or connection strings?As with everything in Visual FoxPro, there are a dozen ways to perform a task. Sometimeseven thirteen ways. And if you ask 13 developers which way is the best, each will argue

    vociferously that their way is the best. So how do you choose? Specifically, what are the prosand cons of DSNs and connection strings?The primary advantage of a DSN is that it is stored in the Windows Registry, which keeps

    it reasonably secure from prying eyes and others who would inadvertently or malevolentlycause problems. (You could even prevent access to it altogether using Windows GroupPolicies, a topic worth investigating but beyond the scope of this book.) Furthermore, it isquite possible to create a routine to check for the DSN upon application startup see Chapter13 of MegaFox, How can I be sure users have the correct settings, for details.

    You could even reinstall the DSN programmatically during startup, exporting the ODBCsettings from the Windows Registry as a .REG file, and then execute it on other machinesusing ShellExecute(), if you needed to. This way users can update settings automatically on

    application startup and DBAs can retain control over connection information.The main disadvantage of DSNs, especially System DSNs, is that they are available to anyapplication running on your system. A fairly smart user then could fire up a copy of, say,Microsoft Excel and connect to your data using the DSN which has the username/passwordstored in it.

    The advantage of connection strings is that they are infinitely flexible, as they are built atrun-time. Its not a difficult task to store connection string parameters in the systems metadata (encrypted, please, since user logins and passwords are part of the package) and retrievethem as necessary. Some developers may feel more comfortable manipulating system metadata instead of having to get into the Windows Registry.

    I personally prefer connection strings to DSNs, but thats just a personal preference. Idont have a passionate view of one over the other, and suggest that you try on both for size,and see which fits to your liking.

    Initial tests with Visual FoxPro and MySQLNow that you have a connection between VFP and MySQL set up and working, its time touse it. You know, create databases and insert records into tables, that sort of fun stuff.

    Fire up VFP, open the Command Window, create a connection, and assign the handle to avariable (I like using a short variable name since Im going to be using it over and over again):

    m.liH = sqlstringconnect("DRIVER={MySQL ODBC 3.51 Driver};" ;

  • 7/31/2019 MySQL Client Server


    Chapter 6: Connecting VFP to MySQL 115

    + ";" ;+ "UID= bob;" ;+ "PWD=secret;)

    Creating a databaseNow that you have a handle, lets work with MySQL. First, we need a database to work with.Lets create one.

    * Create a database to experiment with? SQLEXEC(m.liH, "CREATE DATABASE test_cust")

    In this code segment, were doing a couple of things. Just like you can issue a SQLstatement in the VFP Command Window that works against native VFP tables, you can sendSQL statements to a back-end database via the SQLEXEC command.

    By the way, SQLEXEC (and SQLCONNECT, SQLSTRINGCONNECT, andSQLDISCONNECT) is an example of one of three methods to work with MySQL data fromwithin VFP - SQL Pass Through (SPT). The other two methods, Remote Views andCursorAdaptors, is discussed, along with a more thorough discussion of SPT, in Chapter 15.

    It takes, as you can see, two parameters. (Actually, it can take more, but we just careabout the first two for now.) First, we have to identify which connection were working with,which will identify what database server, and, possibly, which database. Thats taken care of by the m.liH variable, which contains the connection handle.

    Second, we need to send the actual SQL command we wish to execute. For shortcommands (a couple hundred characters or less), you can just enclose the entire command inquotes as shown below. Longer commands require a bit of sleight-of-hand that Ill cover laterin this book.

    Executing the command as shown with the ? will display the return value on the VFPdesktop. If successful, the return value will be 1; if unsuccessful (say, due to a syntax error),the return value will be a -1, like so:

    * Issue a command with incorrect syntax? SQLEXEC(m.liH, "CREATE DBASE test_cust")-1* Now issue a command with correct syntax? SQLEXEC(m.liH, "CREATE DATABASE test_cust")1

    If youve been following along precisely, you probably got a -1 after the correct CREATE

    command this is because you already created the database correctly, and you cant overwritean existing database, so the second attempt failed.Also, if the value of SQLGetProp(m.liH, DispWarnings) = .t., youll get an error that

    looks the dialog shown in Figure 20 .

  • 7/31/2019 MySQL Client Server


    116 MySQL Client-Server Applications with Visual FoxPro

    Figure 20 . If Display Warnings is turned on.

    Youll definitely want to turn that OFF in your applications by issuing aSQLSetProp(m.liH, DispWarnings, .f.) command.

    Youll also find that the incorrect CREATE command moved you off the database that the

    successful CREATE command had created, so youll want to select it again, much like youselect a work area in Visual FoxPro:

    ? SQLEXEC(m.liH, "USE test_cust")

    Again, if you mistype the command, or if test_cust doesnt exist, the SQLEXECcommand will return a -1.

    Its a good time to mention that if youre one of those folks like to type VFP four-letterabbreviations, now is the time to get over it. SPT will not accept crea data test_cust like VFPdoes. Youll also want to get over the habit of using the command USE to open a table.MySQLs use of USE is comparable to VFPs SET DATABASE TO command. Since thereare no objects like VFPs work areas in MySQL, there isnt a comparable MySQL commandto USE either.

    Where is the data created?A directory named test_cust is created under the default data location specified duringinstallation. Ill discuss these values in more detail in Chapter 7 on Configuration.

    In Windows, the default is the data directory under where you installed MySQL(c:\Program Files\MySQL\data) unless you changed either the location of the MySQL installor the default data directory. In Linux, the default data directory is /var/lib/mysql. Details onMySQL data are covered in Chapter 9, Under the Hood.

    Inside the directory, youll see a file named db.opt, which contains the settings (such as

    default character set and collation sequence) for the database you created.

    Working with tables in our new databaseNow that a new database, named test_cust, has been created, the next logical step is to create atable in that database, and then add records to that table:

    * Make sure we're working with the right database? SQLEXEC(m.liH, "USE test_cust")* Create a table in the test database? SQLEXEC(m.liH,"CREATE TABLE cust (cName CHAR(25))")* Insert some rows into the table

  • 7/31/2019 MySQL Client Server


    Chapter 6: Connecting VFP to MySQL 117

    ? SQLEXEC(m.liH,"INSERT INTO cust (cName) VALUES ('Data Schmata 1')")? SQLEXEC(m.liH,"INSERT INTO cust (cName) VALUES ('Data Schmata 2')")? SQLEXEC(m.liH,"INSERT INTO cust (cName) VALUES ('Data Schmata 3')")

    Our last task at the current time (remember, all were doing right now is proving that theconnection does indeed work) is to prove that the data was actually put in the table. We canrun a SQL SELECT command that returns the contents, like so:

    * prove the data was put in - should create a cursor named csrWhatIPutIn,* with the records that were just added? SQLEXEC(m.liH, "SELECT * from cust", "csrWhatIPutIn")

    Youll note a third parameter in the SQLEXEC function this time. This is the name of theresult set that will be created by the SQL SELECT command. If you perform a SQLEXECcommand that returns a result set (i.e. a SELECT as opposed to an UPDATE), VFP will bydefault name the result set sqlresult unless you explicitly provide the name of the result set.

    You always want to name the result set yourself, because VFP will overwrite an existingsqlresult cursor without warning. Even if youre going to throw the cursor away a momentlater, take the time to name it explicitly perhaps, like csrJunk.

    A common mistake (at least for me!) is to forget to enclose the cursor name in quotes if you dont, VFP will try to create a cursor with the name represented by the contents of thevariable csrWhatIPutIn, which more than likely doesnt exist.

    You can also run a SQL SELECT command that returns just the number of rows in thetable, like so:

    * now run a command that creates a cursor named csrHowMany, with* a field named iHowMany, that contains the value 3 (or however* many times you executed the INSERT command)

    ? SQLEXEC(m.liH, "SELECT count(cName) as iHowMany from cust", ;"csrHowMany")

    The SQL statement in this command will generate a record, one field cursor namedcsrHowMany. The value in this field should be the number of records you inserted (3,unless you experimented and added more or less.)

    Youll also note that the command didnt fit onto one line, and so in this example, I usedthe VFP line continuation character to wrap to a second line. Because SQL commands can getquite lengthy and keeping track of semicolons and delimiters can get tedious, a commonworkaround is to store the SQL command in a variable. You can use the TEXT...ENDTEXTcommand in VFP, like so:

    TEXT TO m.lcSQL NOSHOW PRETEXT 3SELECT count(cName) as iHowMany

    FROM custENDTEXT? SQLEXEC(m.liH, m.lcSql, "csrHowMany")

    You can execute all DML (Data Manipulation Language) SQL commands, includingSELECT, INSERT, UPDATE, and DELETE, as well as all DDL (Data Definition Language)SQL commands (CREATE DATABASE, CREATE TABLE, ALTER TABLE, etc.)

  • 7/31/2019 MySQL Client Server


    118 MySQL Client-Server Applications with Visual FoxPro

    Finally, I want to mention that these examples are a classic example of melding VFP withMySQL using SQLEXEC to get data from the database and dropping it into a VFP cursorthat can be manipulated with VFPs rich language constructs.

    Now that were convinced that we can connect to MySQL and work with it a bit, its time

    to close up shop. Use the SQLDISCONNECT command, like so:* Close the connection? SQLDISCONNECT(m.liH)1

    If the disconnect is successful, youll get a return value of 1. An unsuccessful disconnect(say, for example, you used the wrong handle) will generate a negative value.

    The Developer Download files for this chapter, available at , include FirstConnectionTest.PRG. Note that youll need to change the connection stringparameters to reflect the credentials on your machine.

    Listing 1. FirstConnectionTest.PRG.

    * Set up the connection string m.lcXN="DRIVER={MySQL ODBC 3.51 Driver};SERVER=;UID=bob;PWD=secret;"

    * Connect to it and get a handle m.liH=SQLSTRINGCONNECT(m.lcXN)

    * Create a database to experiment with? SQLEXEC(m.liH,"CREATE DATABASE test_cust")* Create a table in the test database? SQLEXEC(m.liH,"CREATE TABLE cust (cField CHAR(25))")* Insert some rows into the table? SQLEXEC(m.liH,"INSERT INTO cust (cName) VALUES ('Data Schmata 1')")? SQLEXEC(m.liH,"INSERT INTO cust (cName) VALUES ('Data Schmata 2')")

    ? SQLEXEC(m.liH,"INSERT INTO cust (cName) VALUES ('Data Schmata 3')")* prove the data was put in - should create a cursor named csrWhatIPutIn,* with the records that were just added? SQLEXEC(m.liH, "SELECT * from cust", "csrWhatIPutIn")* now run a command that creates a cursor a cursor named csrHowMany,* with a field named iHowMany, that contains the value 3 (or however* many times you executed the INSERT command)? SQLEXEC(m.liH, "SELECT count(cName) as iHowMany from cust", ;

    "csrHowMany")* Close the connection? SQLDISCONNECT(m.liH)

    Conclusion/SummaryNow youve proven that MySQL is running and you can connect to it from Visual FoxPro. Formany developers, reaching this point is the Holy Grail, and indeed, it can be frustrating toassemble all the steps just to get this far. But were just beginning the adventure. In the nextcouple of chapters, we direct our attention to working with MySQL directly. Once we havethose tools in our arsenal, well start building a Visual FoxPro application with MySQL.

    Updates and corrections to this chapter can be found on Hentzenwerkes Web site, . Click Catalog and navigate to the page for this book.
  • 7/31/2019 MySQL Client Server


    Chapter 7: Configuring MySQL 119

    Chapter 7Configuring MySQL

    MySQLs operation is controlled by a configuration file. You can use a graphical front-end, called the MySQL Administrator, to change this file, or you can edit this file directly.In this chapter, Ill first show you how to install and use the Administrator. Once yourecomfortable with this tool, Ill cover the essential configuration items youll want to lookat and possibly tweak yourself, and then briefly cover the rest of the settings. Finally, Illdiscuss how to edit the configuration file directly.

    The MySQL configuration file is a plain text file that is referenced during the startup of theMySQL server as well as MySQL client applications. The documentation inside the file isoutstanding, and I urge you to read through it even if youre not planning on ever editing it

    directly yourself.But first, you need to know where to find it.

    The MySQL configuration fileThe configuration files used by MySQL are structured in a very flexible manner.Unfortunately, in this situation, flexible is marketing-speak for confusing, because differentplatforms use different, but also overlapping, files.

    my.ini in WindowsOn Windows, MySQL server looks for a file named my.ini. While the my.ini file is typically

    in the same directory as the mysql executable, an argument is passed to the MySQL servicecommand that explicitly identifies where this file is.On Windows, the syntax looks like this:

    "C:\mysql\bin\mysqld-nt" --defaults-file="C:\mysql\my.ini" MySQL

    You can find out what my.ini file is being used in your Windows installation via theServices applet. Click on the Services applet in the Administrative Tools window in ControlPanel to open the Services list, as shown in Figure 1 .

  • 7/31/2019 MySQL Client Server


    120 MySQL Client-Server Applications with Visual FoxPro

    Figure 1 . Locating the MySQL service in the Services applet.

    Right click on the MySQL service and select Properties to bring forward the Properties dialogas shown in Figure 2 .

  • 7/31/2019 MySQL Client Server


  • 7/31/2019 MySQL Client Server


  • 7/31/2019 MySQL Client Server


    Chapter 7: Configuring MySQL 123

    Clicking the link takes you to a list of files for various operating systems, as shown inFigure 4 .

    Figure 4 . Identifying the specific MySQL Administrator downloads.

    Clicking the download link in the Windows section will eventually download a file named


    (or later) to your hard disk; clicking the download link in the SUSE Linux 9.3 section willdownload a file named


    in a similar manner.

  • 7/31/2019 MySQL Client Server


    124 MySQL Client-Server Applications with Visual FoxPro

    Installing the Administrator

    On WindowsRight-click on the .msi file you just downloaded and select the Install option from thecontext menu. Doing so displays the starting dialog as shown in Figure 5 .

    Figure 5 . Starting up the Administrator Wizard in Windows.

    Clicking the Next button brings you to the license screen, shown in Figure 6 .

    Figure 6 . The Administrator license agreement.

  • 7/31/2019 MySQL Client Server


    Chapter 7: Configuring MySQL 125

    Clicking the Next button takes you to the Destination Folder dialog. At this point, thedefault is usually under C:\Program Files if you changed the default installation directory of MySQL to something like C:\mysql, then I suggest you change the installation directory of theadministrator also so it is still under the main MySQL directory, like so:


    Figure 7 shows the Administrator under Program Files.

    Figure 7 . Pointing to the installation directory for the Administrator.

    Choose the Custom install if you want to control which components are installed. Thereare only two; one of which is optional, so its not that big a deal. Still, I usually chooseCustom, as shown in Figure 8 , so I can see whats included.

  • 7/31/2019 MySQL Client Server


    126 MySQL Client-Server Applications with Visual FoxPro

    Figure 8 . Selecting the type of installation.

    Figure 9 shows you the two components the Administrator itself and a SystemTray Monitor, which I recommend you include since it takes virtually no space and isdarn tootin handy.

    Figure 9 . Selecting the Administrator components.

  • 7/31/2019 MySQL Client Server


    Chapter 7: Configuring MySQL 127

    Now its time to do the install, as shown in Figure 10 .

    Figure 10 . Executing the installation.

    The thermo bar will scroll across for a minute or so, as seen in Figure 11 .

    Figure 11 . Waiting for the installation to complete.

  • 7/31/2019 MySQL Client Server


    128 MySQL Client-Server Applications with Visual FoxPro

    And then youre done as shown in Figure 12 .

    Figure 12 . Success!

    If youre not installing on Linux, move on to the section titled Running theAdministrator.

    On LinuxAssuming you put the RPM file in the zips directory under your home directory, you cansimply enter

    rpm -i /home//zips/mysql-a

    and hit the Tab key to take advantage of the command completion feature in Linux, andthen press Enter to install manually.

    You could also use YaST (Yet another Setup Tool). Double-click on the RPM file inKonqueror and select the Install package with YAST button as shown in Figure 13 ; orselect the file in Konqueror, right-click, select Actions, and then Install with YaST.

  • 7/31/2019 MySQL Client Server


    Chapter 7: Configuring MySQL 129

    Figure 13 . Installing MySQL Administrator via YaST.

    You should then get the root user needed dialog, as seen in Figure 14 ,

    Figure 14 . Installation requires root permission.

    The blank YaST screen appears. Enter mysql in the search text box and youll get abunch of packages, including the one you highlighted. Note that other packages are part of theSuSE install, and thus are probably older than what you installed in Chapter 4.

    Select the Administrator as shown in Figure 15 , and then click the Accept button in thelower right.

  • 7/31/2019 MySQL Client Server


    130 MySQL Client-Server Applications with Visual FoxPro

    Figure 15 . Identifying the MySQL Administrator package in YaST.

    Youll get the mysql-administrator package installation thermometer bar in the bottom of the screen as shown in Figure 16 .

    Figure 16 . Executing the package installation.

    Once finished, close the dialog, and youre all set to run the Administrator.

  • 7/31/2019 MySQL Client Server


    Chapter 7: Configuring MySQL 131

    Running the AdministratorIn my opinion, the best way to run the MySQL Administrator in Windows is through theMySQL System Tray Monitor. On Windows, the System Tray Monitor should have beeninstalled along with the rest of the MySQL Administrator process.

    If it wasnt (perhaps you forgot to select the option or Windows hiccupped during theinstallation), you can install the monitor into the System Tray via the Start | MySQL | MySQLSystem Tray Monitor menu option. Doing so will run the System Tray Monitor whichplaces an icon that looks like a life preserver with a blue bar on its right side into the SystemTray, as shown in Figure 17 (immediately to the left of the time).

    Figure 17 . The MySQL Monitor context menu.

    Right clicking on the MySQL System Tray Monitor icon displays the context menu alsoshown in Figure 17. Launch the MySQL Administrator via its menu option. (Note that if yourun the System Tray Monitor before installing an option, such as the Query Browser, thatoption will appear disabled until you close the monitor and open it again.)

    In Linux, you can either select the Applications, MySQL Administrator menu option fromthe Gecko start menu button, or execute /usr/bin/mysql-administrator from a command

    prompt.In both cases, youll be greeted by the login screen displayed in Figure 18 .

  • 7/31/2019 MySQL Client Server


    132 MySQL Client-Server Applications with Visual FoxPro

    Figure 18 . The MySQL Administrator login screen.

    On Windows, you may be asked to poke through your firewall. Figure 19 showsZoneAlarm prompting said action.

    Figure 19 . Giving the Administrator permission to the ZoneAlarm firewall.

    Once you open the MySQL Administrator, youll be greeted with a window like that inFigure 27. Well come back to this dialog in a minute. First, lets go over the various optionsin the login dialog from Figure 18.

  • 7/31/2019 MySQL Client Server


    Chapter 7: Configuring MySQL 133

    Advanced login optionsSome of the default options for the Login dialog were shown in Figure 18: Server Host of localhost and Port of 3306. Obviously the username and password will be differentaccording to your own installation and how youve created user accounts.

    First, you can choose to connect to a MySQL server running on a different machine byentering that machines name or IP address in the text box. For example, if the machine thatMySQL is running on is on the same network and is named herman, you would just enter

    Server Host: herman

    If you wanted, you could use the IP address of the machine, like so:

    Server Host:

    While MySQL is configured by default to allow connections via port 3306 (thats the

    connections to the server, not your client), some installations may change that port number. If you need to connect to a MySQL server that listens on a non-standard port, enter that port intothe Port text box:

    Port: 9906

    You should create a profile called a Stored Connection for your server. (If you routinelyconnect to more than one MySQL server, you can create a connection for each server.) Inorder to create a stored connection, click on the ellipses button to the right of the StoredConnection combo box. Youll get the Connections dialog shown in Figure 20 .

  • 7/31/2019 MySQL Client Server


    134 MySQL Client-Server Applications with Visual FoxPro

    Figure 20 . Creating a profile for a connection.

    Click on Add new Connection to make the text boxes in the Connection Parameters tabeditable, as shown in Figure 21 .

  • 7/31/2019 MySQL Client Server


    Chapter 7: Configuring MySQL 135

    Figure 21 . Creating the connection for a new profile.

    Enter a text string for what you want to call the connection (this string will show up in theStored Connections combo box shown in Figure 18.) While some folks tend toward usingwhimsical names for their connections (Happy, Sleepy, Grumpy, etc.), or worse,generic names (Connection1, Test2, Database), I find I cant remember whats on theother end of a name like this. Instead, Ill try to provide some specific details about where Imconnecting, such as the name of the box, the IP address, and/or the OS on the box. If I wasflipping between multiple versions of MySQL, Id probably include that info too.

    Dont bother with the Password if youre creating a connection of Type MySQL (seethe combo box three rows below the Connection text box), as by default its not stored withthe connection and youll have to type it in when you select the Stored Connection in theLogin dialog later.

    If you want to have the password stored as part of the connection, you can select theStore Passwords in the General Options node as shown in Figure 22 .

  • 7/31/2019 MySQL Client Server


    136 MySQL Client-Server Applications with Visual FoxPro

    Figure 22 . General options for the profile.

    Note that you can choose to have your password stored in one of three methods.Once youre done dealing with the password, enter the attributes of the MySQL server

    that this connection is going to connect to (back in Figure 21.) The Hostname of the server canbe localhost, a machine name, or an IP address. The Port is typically 3306, but might bedifferent depending on special needs. Keep the Type set to MySQL.

    Since youre creating a connection for the MySQL Administrator, you wont enter aSchema (the name of a database), but if you were creating a connection for use with the QueryBrowser, you could enter one if you wanted.

    Finally, add notes if desired. The result is shown in Figure 23 .

  • 7/31/2019 MySQL Client Server


    Chapter 7: Configuring MySQL 137

    Figure 23 . A completed connection, before it is saved.

    After clicking the Apply button, the name of the connection will be displayed under theConnections node in the tree view control, as shown in Figure 24 .

  • 7/31/2019 MySQL Client Server


    138 MySQL Client-Server Applications with Visual FoxPro

    Figure 24 . A saved connection for a profile.

    Click the Close button in the lower right corner, and the Login dialog with thenewly created connection selected will be displayed, ready for you to log in to the server.See Figure 25 .

  • 7/31/2019 MySQL Client Server


    Chapter 7: Configuring MySQL 139

    Figure 25 . Selecting a profile.

    One final note: If you installed the Query Browser (see Chapter 8), the Query Browsermenu option in the MySQL Administrator will be enabled. When you click on the QueryBrowser menu option in the MySQL System Tray Monitor, youll get one more control in theLogin dialog, as shown in Figure 26 .

    Figure 26 . The MySQL Login dialog displayed from the Query Browser.

  • 7/31/2019 MySQL Client Server


    140 MySQL Client-Server Applications with Visual FoxPro

    The Default Schema text box allows you to specify which database you want to startworking with in the Query Browser. Details are in Chapter 8, The Interactive Use of MySQL. It will be filled in automatically if you enter a Schema when creating a connectionas described above.

    Even though this text box doesnt show up when you select the MySQL Administratormenu option, I wanted to point out this one subtle difference now, in case you accidentallychose the wrong menu option in the MySQL System Tray Monitor, and couldnt figure outwhy that extra text box was showing up.

    Click OK to connect. Now on to the Administrator.

    The AdministratorThe MySQL Administrator has 11 sections, grouped into nodes, and displayed in the left-sidepane of the main window as shown in Figure 27. If you select Configure Instance in theMySQL System Tray Monitor context menu (Figure 17), youll get an abbreviated version of the Administrator, with only the Service Control, Startup Variables, and Server Logs nodes in

    the left-side pane.Additionally, if you connect to a remote server, several of the nodes will be disabled:

    Service Control, Startup Variables, and Server Logs.

    Figure 27 . The main Administrator screen.As you can see from the various nodes in the list in the left panel, the MySQL

    Administrator gives you the ability to manage all aspects of the MySQL server from aconvenient graphical user interface. In this chapter, we will be primarily concerned withconfiguring MySQL so we can start using it; administration will come later after wevedeveloped a need for more than the ability to start and stop the server.

  • 7/31/2019 MySQL Client Server


    Chapter 7: Configuring MySQL 141

    The Service Control nodeClicking on the second node, Service Control, opens the Start/Stop Service tab, as shown inFigure 28 .

    Figure 28 . The Service Control node allows you to start and stop the server without having to mess with the operating system mechanisms.

    From here, you can start and stop the MySQL service via the Stop Service button

    (which changes to Start Service after you stop the service). When you start or stop theservice, logging messages display in the Log Messages text box. This feature is particularlyhandy in that you have to stop and start the server for changes made to the configuration, bothin the MySQL Administrator as well as manually.

    The Configure Service tab in the Service Control node, shown in Figure 29 , allows you toset various parameters regarding the service.

  • 7/31/2019 MySQL Client Server


    142 MySQL Client-Server Applications with Visual FoxPro

    Figure 29 . The Configure Service tab of the Service Control node allows you to specify aspects of the service startup.

    Before I get started on the contents of the form, note the scroll bar on the right side onceyou make changes, you may need to scroll the form down to find the Apply Changes andDiscard Changes buttons theyre not visible on the form as its shown in Figure 29.(Depending on your screen resolution, you may be able to see the entire form.) The buttons areshowing in Figure 30 as well as the last few options. You could also resize the form via theresizer in the lower right corner of the form in order to see more.

    By default, the MySQL service is automatically started; thus, the Launch MySQL serverautomatically checkbox will be selected. You can turn that flag off, as well as change the nameof the service as it displays in the Properties dialog of the Services applet (shown way back inFigure 2). This can be handy if you install multiple versions of MySQL and need to keep themstraight MySQL 4.0, MySQL 4.1, and MySQL 5.0 are easier to work with thanMySQL, MySQL1, and MySQL2.

    You can also use this tab to point to a different configuration file. Just type its name andpath in the text box. If the file doesnt already exist, the string you type in will be displayed inred, as shown in Figure 30. Once you save your changes, the startup string for the service (youcan see it in the Properties dialog in Figure 2) will reflect your new configuration file.

  • 7/31/2019 MySQL Client Server


    Chapter 7: Configuring MySQL 143

    Figure 30 . Invalid values entered in text boxes are displayed in red.

    The Launch MySQL server automatically and Config filename settings are bothstored in the Services applet in Windows and modify the scripts contained in /etc/init.d onLinux.

    The Startup Variables nodeThe next thing you will typically want to do is point to your database. These options are foundin the Startup Variables node, as shown in Figure 31 .

  • 7/31/2019 MySQL Client Server


    144 MySQL Client-Server Applications with Visual FoxPro

    Figure 31 . Pointing to the database in the configuration file.

    Youll see that this node has lots and lots of tabs. There are two things that arent quite asobvious as this abundance of tabs.

    The first, which is a completely non-standard user interface mechanism, is the littlepicture with a red X to the left of various options. For example, theres one to the left of the

    disabled Temp directory in the Directories box in Figure 31. This is a toggle that actsmuch like a checkbox, interestingly enough. As shown in Figure 31, the Temp directory field,although not grayed out, cant be typed in, which means you cant enter a temporary directorypath.

    Click on the icon with the red X and the red X disappears, so it looks like the icons forBase directory and Data directory. Once you do so, you can enter a path in the text box.Doing so, as making other changes does as well, enables the Apply changes and Discardchanges buttons in the lower right corner.

    As mentioned before, another thing that isnt immediately obvious is the dialog is avariable height form. You can drag the lower right corner of the dialog to make the form taller,and thus be able to see more controls without scrolling. For example, in Figure 31, I stretchedthe form down so that the scroll bar disappeared I wanted the General box at the bottom of the tab to display. By default, that box is out of sight.

    Also note that the name of the file that stores this information is displayed in the bottomof the form in Figure 31 it says C:\mysql\my.ini. Yours may be C:\ProgramFiles\MySQL\MySQL 5.0\my.ini.

    General Parameters Depending on how you installed MySQL to begin with, your settings for Base directory,Data directory, and Default storage may differ from what is shown in Figure 31.

  • 7/31/2019 MySQL Client Server


    Chapter 7: Configuring MySQL 145

    Furthermore, once you finish your install, you may wish that youd made different choices.The General Parameters tab is where you rectify those decisions.

    The Default storage combo box has four choices: MyISAM, InnoDB, BDB (BerkeleyDatabase), and Heap. This setting will control the type of database or table created if you dont

    explicitly identify the table type in your SQL CREATE statement.(For details about the various storage types, see Chapter 14, Storage Engines and TableTypes, in the on-line help.)

    As a result, its possible to create some tables in a database with one type and other tablesin the same database of another type. For example, the default database type is InnoDB. Youcan open an InnoDB database and then manually add another table to it, explicitly specifyingMyISAM as the type. Some readers prefer to mix and match MyISAM and InnoDB tables inthe same database, using each storage engine for specific purposes. MyISAM tables aresignificantly faster, and thus are a good choice for write-once, read-many tables like error logs,audit trails, and query-intensive data warehouse files. InnoDB tables, on the other hand, sincethey support transactions, albeit at a cost of some performance, are good for the workhorse

    tables in the database.The Base directory identifies where the executable is. As the label on the dialog says,other paths (meaning relative paths) are resolved relative to the base directory. Youllprobably want to leave this alone.

    The Data directory, on the other hand, is potentially of much interest, particularly if youmissed the step during installation where you could specify where you wanted your data tolive. It contains three different things.

    First, the root data directory contains the location for the log and error files, prefixed withthe name of the machine, so if your machine name was frodo,, the MySQL log file would benamed frodo.log and the MySQL error file would be called frodo.err. The root alsocontains a pid (Process ID) file of the current MySQL instance, also named with themachine name, such as If you shut down the instance, the PID file goes away.

    Second, there is a subdirectory named mysql. This directory contains the meta-data forMySQL tables that identify the hosts, databases, table schemas, privileges, and so on. Evenif you use a non-MyISAM database type, these tables are used by MySQL.

    Finally, there are additional subdirectories (on the same level as the mysql subdirectory) one for each MyISAM MySQL database identified in the meta-data.

    If you change the Data directory value, note that youll need to move the contents of theoriginal directory to the new location, or else the server wont be able to find the meta-data orthe databases the meta-data references.

    MyISAM parameters The MyISAM parameters tab of the Startup Variables node doesnt contain any options thatyoull typically want to modify as youre getting started.

    InnoDB parameters The InnoDB parameters tab of the Startup Variables node is another story, though, if youreusing the InnoDB storage engine. Figure 32 shows part of the tab, as its another one of thosescroll down jobbies.

  • 7/31/2019 MySQL Client Server


    146 MySQL Client-Server Applications with Visual FoxPro

    Figure 32 . The InnoDB tab of the Startup Variables node.

    First, youll want to make sure the Activate InnoDB checkbox is selected. This settingcorrelates to the


    setting in the configuration file. If this setting (in the file) has a leading #, it means that itis commented out, and thus MySQL will NOT skip InnoDB in other words, InnoDB will beused. If its not commented out, like so:


    the InnoDB storage engine will be activated. Doncha just love double negatives? (Ormaybe that should be Doncha not hate double negatives?)

    Next, you can change the location for the InnoDB databases if you dont want them in thedefault data directory. Do this by scrolling down to the Data directory text box in theDatafiles box and entering the path for your InnoDB data files. By default, all of the tablesin InnoDB databases are contained in a single file.

    Other parameters Depending on your application, you may need to tweak the Max Connections parameter in theNetworking tab. Other than that, were not going to bother with the parameters in any of theother tabs, such as Performance, Log files, Replication, and so on. You may want to scanthrough the controls in each tab, just to see if any light a particular fire for your particularscenario, but Id argue that most readers will want to get on to the rest of the Administrator.

  • 7/31/2019 MySQL Client Server


    Chapter 7: Configuring MySQL 147

    The User Administration nodeThe User Administration node allows you to add, delete, and edit users and their privilegeswithout having to manually work with the GRANT command as we did in the installationchapters. Selecting the User Administration node will display all of the MySQL users in the

    Users Accounts list box below the list of nodes. Selecting a user in the Users Accounts list boxwill then display that users account information in the User Information tab, as shown inFigure 33 .

    Figure 33 . The User Administration tab allows you to visually manage users and

    their permissions.

    Once you add a user, you can see which databases the user has access to, and theirspecific rights for each database. Click on the Schema Privileges tab, and then select a specificscheme in the list box on the left.

    Figure 34 shows that the user bob has SELECT, INSERT, and UPDATE privileges tothe TESTISAM database.

  • 7/31/2019 MySQL Client Server


    148 MySQL Client-Server Applications with Visual FoxPro

    Figure 34 . Visually setting permissions for user bob.

    You can fine-tune the rights for each user, giving each person specific abilities on adatabase by database basis.

    If you havent already, youll want to create a user for your day-to-day use. WhileWindows has always been lax about encouraging you to run as a non-Admin user, the OpenSource software world isnt quite so forgiving. Logging on a Microsoft SQL Server as admin

    with an sa password wouldnt even raise an eyebrow in many installations, but logging in asroot on a MySQL server will generate reactions ranging from mild disapproval to outrightridicule from the surrounding folks.

    So set that work-a-day user up now!

    Other nodesThe other nodes in the list are used during various system maintenance tasks. While we dontneed to discuss them now, I suggest you take a moment or three to click on each node andexamine the functions in each of them. Well revisit them as appropriate later in the book.

    Editing the my.ini/my.cnf file directlyThe MySQL configuration file carries on the tradition of excellent commenting in the file;indeed, after looking through the file, you may conclude that you dont need to read anythinghere about how to change the settings (and youd be mostly right.)

    When you make a change to the configuration file in the Administrator, the previousversion is automatically backed up, so you can easily roll back to a previous version. If youspend some time goofing around with various settings, dont be surprised to find a dozen ormore files, looking like this:

    my.bak1 my.bak2

  • 7/31/2019 MySQL Client Server


    Chapter 7: Configuring MySQL 149

    my.bak3 my.bak4 my.bak5 my.bak6 my.bak7 my.ini

    in the MySQL root directory.That said, if you want to try modifying the configuration file by hand, dont forget to

    make a backup, and remember that youll need to stop and start the server in order foryour new settings to take effect!

    Specific settings in the MySQL configuration fileThe easiest way to learn to directly modify the file is to make the desired changes in theMySQL Administrator, and then open up the file and see what has changed. Here are a coupleof items in the configuration file that match the settings I discussed earlier in this chapter.

    First, look for the section that starts with these lines:# SERVER SECTION# ----------------------------------------------------------------

    Underneath, youll see a couple of path statements:

    #Path to installation directory.... basedir="C:/mysql/"

    #Path to the database rootdatadir=e:/wsdb/mysqlisam/

    These match to the values in Figure 31. A little below those lines is the specification forthe default storage engine:

    # The default storage engine that will be used when creating new tablesdefault-storage-engine=innodb

    The setting for MyISAM tables looks like this:

    # default-storage-engine=myisam

    Later on in the configuration file, there are sections for MyISAM and InnoDB specific

    options, identified by the headings:

    #*** MyISAM Specific options


    #*** INNODB Specific options ***

    Its educational to manually change settings in the configuration file, and then open up theMySQL Administrator to see how those manual changes are reflected in the GUI.

  • 7/31/2019 MySQL Client Server


    150 MySQL Client-Server Applications with Visual FoxPro

    Conclusion/SummaryThe MySQL configuration is one of those things that youll typically set up once and thenleave alone until a special need comes along. The MySQL Administrator, as a result, is ahandy tool for modifying the configuration file without having to remember how the plumbingunder the hood is constructed.

    Now that MySQL is running and configured, its time to start working with data for real.In the next chapter, well explore how to use the MySQL Query Browser to work withMySQL data interactively.

    Updates and corrections to this chapter can be found on Hentzenwerkes Web site, . Click Catalog and navigate to the page for this book.
  • 7/31/2019 MySQL Client Server


    Chapter 8: The Interactive Use of MySQL 151

    Chapter 8The Interactive Use of MySQL

    Once the database server is up and running, and you have proven that you can connectto it from Visual FoxPro, what next? Youll need to get comfortable using MySQL inan interactive way creating databases and tables, and then adding, editing, anddeleting data from those structures. In this chapter, Ill discuss using the MySQL QueryBrowser to work with MySQL in an interactive session. After covering installation, Illtour the various parts of the interface, and then show how to use it to perform datadefinition (creating databases and tables) as well as data manipulation (querying,adding, updating, and deleting data). Finally, Ill provide pointers to some popular thirdparty replacements.

    One of the big wins for Visual FoxPros granddaddy, dBASE II, was that it consisted of bothan interactive environment and a programming language. The interactive environment allowedyou to directly manipulate data in tables, much like VisiCalc enabled you to work withelectronic spreadsheets and WordStar allowed you to do personal word processing. Other so-called database tools also allowed you to perform these functions. The difference withdBASE II was that the programming language was really a full-fledged developmentenvironment, not just a simple scripting language. You could go way beyond the basicautomation of simple tasks and create robust programs with logic trees, database manipulation,and subroutines once you found your way around the environment.

    But it was important that you understood how to create and modify tables, navigate yourway through those tables, including setting up relations between tables, and make changes to

    the data in the tables the timeless add/edit/delete operations.Similarly, youll find that you need to know how to do the same types of things withMySQL in an interactive environment before you begin to programmatically work withMySQL databases.

    There are a number of GUIs that provide interactive access to a MySQL database. TheQuery Browser is produced by MySQL A.B. themselves, but there are others as well. Thischapter will focus on the Query Browser, but at the end, well take a look at several other thirdparty tools as well.

    Installation of the MySQL Query BrowserInstallation varies a bit according to whether youre running on Windows or Linux.

    Windows downloadGo to http:\\ , select Downloads, and select the MySQL Query Browser link under the MySQL Tools heading. Youll go to a new page that contains all of the QueryBrowser versions Windows, Linux, Mac, and so on. Under the Windows downloadsheading theres a single link for x86. Clicking on Pick a mirror will eventually get you to alink that looks something like this:


  • 7/31/2019 MySQL Client Server


    152 MySQL Client-Server Applications with Visual FoxPro

    (The exact version number may change by the time you read this, of course.)

    Linux downloadGo to http:\\ , select Downloads, and select the MySQL Query Browser link

    under the MySQL Tools heading. Youll go to a new page that contains all of the QueryBrowser versions Windows, Linux, Mac, and so on. Under the Linux x86 generic RPM(statically linked against glibc 2.2.5) downloads heading, there are two links, one for non-SUSE RPM installations and the other specifically for SUSE 9.3. Clicking on Pick a mirrorwill eventually get you to a link that looks something like this:

    Linux (x86, libc6):


    SUSE LINUX 9.3 (x86):


    Again, the exact version number may change by the time you read this.

    Windows installationAfter you download the file to your standard location for such items, right click on the file inWindows Explorer (or your favorite replacement for Explorer), and select Install. (If you arerunning Windows NT or 2000, you may have to install the Windows Installer first, but youprobably already have it on your machine.)

    The MySQL Query Browser Setup Wizard starts, as shown in Figure 1 .

    Figure 1 . The MySQL Query Browser setup starts with the standard Welcome screen.

  • 7/31/2019 MySQL Client Server


    Chapter 8: The Interactive Use of MySQL 153

    And proceeds to the License screen, as shown in Figure 2 .

    Figure 2 . The traditional License screen.

    Which then is followed by the dialog that allows you to change where the Query Browserwill be installed, as shown in Figure 3 . I suggest that you put it under the directory where youinstalled MySQL to begin with.

    Figure 3 . Selecting where the Query Browser will be installed.

    The Wizard then asks you to confirm your choice, as shown in Figure 4 .

  • 7/31/2019 MySQL Client Server


    154 MySQL Client-Server Applications with Visual FoxPro

    Figure 4 . Confirming your choice of installation location.

    You can choose either a complete or a custom install, as shown in Figure 5 .

    Figure 5 . Choosing a complete or custom installation.

    If you choose Custom, youll be prompted to choose which components to install andwhen, as shown in Figure 6 (somewhat moot with the Query Browser.)

  • 7/31/2019 MySQL Client Server


    Chapter 8: The Interactive Use of MySQL 155

    Figure 6 . Selecting the components during a custom install.

    Once you make all your choices, youll be prompted to review them, and then execute theinstallation, as shown in Figure 7 .

    Figure 7 . Confirming your choices and then executing the installation.

  • 7/31/2019 MySQL Client Server


    156 MySQL Client-Server Applications with Visual FoxPro

    Once complete, youll be greeted with the Wizard Completed screen as shown in Figure8.

    Figure 8 . Wizard complete!

    Once you click Finish, youre ready to begin usi