Welcome. This MySQL tutorial is a guide for new MySQL users, providing a reference of very basic, step by step, instructions on how to get started. This MySQL help page also gives more advanced users assistance in upgrading and running multiple versions of MySQL on a computer at the same time.
MySQL is an SQL based relational database management system (DBMS) that runs under a broad array of operating systems. MySQL is frequently used by PHP and Perl scripts. The SQL commands discussed in this tutorial apply to MySQL operating under all operating systems. Only the installation instructions are Windows specific. The focus is on Windows XP Professional and Windows 2000 Professional machines.
We'll be covering the installation of MySQL versions 5.0.51b, 4.1.16 as well as how to configure everything so they'll all be able to run on your system at the same time. Plus, the data directories will be moved to another location in order to make backups easier. If you only want to install one version of MySQL, ignore the instructions relating to the other versions.
If your operating system or versions of MySQL are different, the instructions should still work, but keep an eye out for slight differences, like which working directory you'll need to be in.
Usage:
Commands to type in and items that require appropriate substitutions are displayed like this.
Resulting screen text looks like this.
File names appear in this fashion.
Log in to your computer using an account having Administrator privileges.
If you're not upgrading, just skip down to the next section.
If you are upgrading, there are MANY changes that you HAVE TO be aware of. Carefully read the pages in the MySQL manual that apply to you. If you intend to jump over a release series in your upgrade (e.g.: going straight from 4.0 to 5.0) you are strongly advised NOT to do so. You should do the upgrade process one release series at a time (e.g.: go from 4.0 to 4.1, then to 5.0).
Here's a quick rundown of how to save your old MySQL data so it can be used in your new system.
The next step gives you choices of which components to install and where to install it.
Click the "Change" button at the bottom right of the dialog box and put in C:\program files\mysql50\ then click "OK"
If you're upgrading, make sure to click on the plus sign next to the "Developer Components" item, then click on "Scripts, Examples" and set it to "This feature will be installed on the local hard drive."
Adjust the other entries per your desires. Make sure the "MySQL Server" and the "Client Programs" are selected. Once you have everything lined up as you want, click "Next."
mkdir mysql50 mkdir mysql50\data mkdir mysql50\data\mysql mkdir mysql50\ibdata mkdir mysql50\iblogs
mkdir mysql41 mkdir mysql41\data mkdir mysql41\data\mysql mkdir mysql41\ibdata mkdir mysql41\iblogs
copy "C:\program files\mysql50\data\mysql" mysql50\data\mysql
copy "C:\program files\mysql41\data\mysql" mysql41\data\mysql
I suggest putting empty my.cnf files in place in order to keep your MySQL servers from being subverted. While this step isn't strictly necessary, it's better to be safe than sorry. We'll do this via the Command Prompt window we were using above.
Be aware that Windows considers .cnf files to be a "SpeedDial" configuration file and automaticlaly hides the file extension. You can make the extension visible via Windows Explorer's "hide file extensions" option (Tools | Folder Options | View). Also note that Windows Server 2003 hides the extension even if this option is turned off.
copy mysql50\data\my.cnf "C:\program files\mysql50\data"
copy mysql41\data\my.cnf "C:\program files\mysql41\data"
copy mysql50\data\my.cnf "C:\program files\mysql50\data" copy mysql50\data\my.cnf mysql41\data copy mysql50\data\my.cnf "C:\program files\mysql41\data"
In notepad, paste in the following, then adjust the the port numbers and drive letters and paths as needed.
NOTE: This sample file puts 5.0.x on the default port (3306) and 4.1.x on 3341. These port numbers will be used throughout the rest of the tutorial. So, if you change anything in your my.cnf file, you will need to adjust all of our commands accordingly. On the command line, MySQL uses the -P flag to tell the client which port to connect to, for example -P 3341.
# This config file contains settings for MySQL versions # 5.0.x and 4.1.x. Be aware that only one server # instance can be on a given port. This sample puts # version 5.0.x on MySQL's default port, 3306. Adjust # the port numbers to suit your situation. [mysql] # Displaying the version number in the prompt # helps when running multiple instances. prompt = mysql\\_\v>\\_ [mysqld-5.0] port = 3306 basedir = C:/Program Files/mysql50/ datadir = M:/mysql50/data/ innodb_data_home_dir = M:/mysql50/ibdata/ innodb_log_group_home_dir = M:/mysql50/iblogs/ innodb_data_file_path = ibdata1:10M:autoextend # Make table names case sensitive. # Ensures portability when moving applications to other os's. set-variable = lower_case_table_names=0 # Roll back entire transactions that time out, # OPTION AVAILABLE SINCE 5.0.32. innodb_rollback_on_timeout = 1 [mysqld-4.1] port = 3341 basedir = C:/Program Files/mysql41/ datadir = M:/mysql41/data/ innodb_data_home_dir = M:/mysql41/ibdata/ innodb_log_group_home_dir = M:/mysql41/iblogs/ innodb_data_file_path = ibdata1:10M:autoextend # Make table names case sensitive. # Ensures portability when moving applications to other os's. set-variable = lower_case_table_names=0
Let's lock down the file
permissions on the directories we created by
entering the following commands into a Command Prompt:
cacls C:\my.cnf /g administrators:f system:r "authenticated users":r
If you may get the following error message: The cacls command can only be run on disk drives that use the NTFS file system. Don't worry about it (for now). Skip all the cacls commands in the rest of our tutorial.
Enter each line below separately because some of them require user confirmation.
cacls M:\mysql50 /t /g administrators:f system:f mysql:c cacls M:\mysql50\data\my.cnf /t /g administrators:f system:r cacls "C:\program files\mysql50" /t /g administrators:f system:f mysql:r "authenticated users":r cacls "C:\program files\mysql50\data" /t /g administrators:f
cacls M:\mysql41 /t /g administrators:f system:f mysql:c cacls M:\mysql41\data\my.cnf /t /g administrators:f system:r cacls "C:\program files\mysql41" /t /g administrators:f system:f mysql:r "authenticated users":r cacls "C:\program files\mysql41\data" /t /g administrators:f
If System error 1069 has occurred comes up, your passwords didn't match. You can create a new password by typing net user mysql * into the Command Prompt. Then put that new password into the MySQL services' properties' "Log On" tab.
Getting a System error 5 has occurred indicates problems getting to the directory containing the MySQL executables (for example, insufficient permissions).
If you get an error saying System error 1067 has occurred it means a configuration directive in C:\my.cnf couldn't be processed. That can be due to a typographical error in the name or value of a setting. Similarly, the path referred to by the setting's value could be inaccessible due to insufficient permissions.
To help narrow down what's going on, check out the Event Viewer: Start | Run, then type in eventvwr.msc and hit ENTER. Click the "Application" item in the left pane. Now examine the top of the right hand pane for recent MySQL errors. Double click the first item and look at the message in the "Description" box.
Either of the following mean there's a boo-boo in the path value assigned
to the datadir setting in C:\my.cnf:
Fatal error: Can't open privilege tables: Table 'mysql.host' doesn't exist
or
Warning: Can't create test file
In this situation, make sure the actual path is a case-sensitive match to
the path in the configuration file and that the directories in question have
the permissions they need to be accessed by the MySQL daemon. Then
try the net start command again.
Along the same lines, error logs showing
Can't find messagefile 'C:\Program Files\mysql\share\english\errmsg.sys'
points to a mismatch between the basedir value and the actual path
to the MySQL executables.
An unknown variable notice is clear enough, no?
If there are no MySQL related error messages in the Event Log's Application section, you have a major typo in the C:\my.cnf. Perhaps one of the [mysql...] section headings are wrong.
This SQL file was in the scripts directory prior to version 5.0.38.
You can ignore all of the query error messages (for example Unknown column, Duplicate column name, etc).
MySQL has good security controls, but the default installation is wide open. So, if you're doing a new installation, let's close things up before we go any further.
In the following commands, don't forget that if you changed the ports in the my.cnf file, you'll have to adjust the port numbers here.
Activate the "MySQL 50 Shortcut" we created earlier then type in:
mysql -u root mysql
Activate the "MySQL 41 Shortcut" we created earlier then type in:
mysql -u root -P 3341 mysql
(If you get the following error message:
ERROR 2003 (HY000): Can't connect to MySQL server on 'localhost' (10061)
That means the servers didn't stay started. The most likely reason is
the my.cnf file has errors in it. Go back to the Start the
services step and carefully read the section about checking the
Event Viewer logs.)
Once you are logged in, copy the following queries to Notepad and change NewPw to something unique. Now copy that and paste it into the command prompt window(s) you just opened.
delete from user where Host <> 'localhost' and User <> 'root'; delete from db; update user set Password=password('NewPw') where User='root'; flush privileges; exit
If you're using Windows 95, 98 or ME do not run mysqld --install
. These
operating systems don't have the ability to host a "service." So, you need to run MySQL as
a standalone application by executing the command mysqld --standalone
.
I haven't run MySQL on these systems myself, so, for more information, check out the Starting MySQL on Windows 95, 98 or Me and Running MySQL on Windows sections of the manual or explore the MySQL Win32 Mailing List Archive.
We'll be using MySQL 5.0.x here. Adjust the shortcut and port as necessary.
Activate the "MySQL 50 Shortcut" we created earlier and type in
mysql -u root -p
then enter your password when prompted.
You will then see the following output:
Welcome to the MySQL monitor. Commands end with ; or \g. Your MySQL connection id is 1 to server version: 5.0.51b Type 'help;' or '\h' for help. Type '\c' to clear the buffer.
If your root account doesn't have a password on it, the above command won't work for you. You really need to get on top of security. Log in without the password:
mysql -u root mysqlThen set a password (changing "NewPw", of course):
update user set Password=password('NewPw') where User='root'; flush privileges;
If you get an error saying Client does not support authentication protocol requested by server; consider upgrading SQL client when trying to connect, that means your client is from before version 4.1 while the server you are connecting to is using version 4.1 or later. The best solution is to install a current version of the MySQL client.
Database "database01" created.
All that really does is create a new subdirectory in your M:\mysql50\data directory.
Database changed
Query OK, 0 rows affected (0.00 sec)
Enclose entire list of field names between one pair of parentheses.
Commas are used between each field.
A space may be used after the comma between fields.
A comma is not used after last field.
This, and all SQL statements, are concluded by a semicolon ";".
+----------------------+ | Tables in database01 | +----------------------+ | table01 | | table02 | +----------------------+
+---------+----------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +---------+----------+------+-----+---------+-------+ | field01 | int(11) | YES | | | | | field02 | char(10) | YES | | | | +---------+----------+------+-----+---------+-------+
Congratulations! Pretty straightforward, eh?
Query OK, 1 row affected (0.00 sec)
Enclose entire list of field names between one pair of parentheses.
Enclose the values to be inserted between another pair of parentheses.
Commas are used between each field and between each value.
A space may be used after the comma between fields.
+---------+---------+ | field01 | field02 | +---------+---------+ | 1 | first | +---------+---------+
Excellent!
Query OK, 1 row affected (0.04 sec) Records: 1 Duplicates: 0 Warnings: 0
Query OK, 1 row affected (0.04 sec) Records: 1 Duplicates: 0 Warnings: 0
The "add column" must be restated for each column.
Commas are used between each add column statement.
A space may be used after these commas.
The MySQL Manual fully explains each possible column data type.
+---------+---------+---------+---------+---------+ | field01 | field02 | field03 | field04 | field05 | +---------+---------+---------+---------+---------+ | 1 | first | NULL | NULL | NULL | +---------+---------+---------+---------+---------+Now we're getting somewhere!
The MySQL command line interface allows you to put a statement on one line or spread it across multiple lines. There's no difference in syntax between the two. Using multiple lines allows you to break down the SQL statement into steps you may more easily comprehend.
In multiple line mode, the interpreter appends each line to the prior lines. This continues until you enter a semicolon ";" to close out the SQL statement. Once the semicolon is typed in and you hit enter, the statement is executed.
Here's an example of the same exact SQL statement entered both ways:
Single Line Entry mysql 5.0.51b> create table table33 (field01 integer,field02 char(30)); |
Multiple Line Entry mysql 5.0.51b> create table table33-> (field01 -> integer, -> field02 -> char(30)); |
Don't break up words:
Valid | Invalid |
---|---|
mysql 5.0.51b> create table table33
-> (field01 -> integer, -> field02 -> char(30)); |
mysql 5.0.51b> create table table33
-> (field01 inte -> ger, -> field02 -> char(30)); |
When inserting or updating records, do not spread a field's string across multiple lines, otherwise the line breaks are stored in the record:
Standard Operation mysql 5.0.51b> insert into table33 (field02)-> values -> ('Who thought of foo?'); |
Line Break Stored in Record mysql 5.0.51b> insert into table33 (field02)-> values -> ('Pooh thought -> of foo.'); |
Results mysql 5.0.51b> select * from table33;+---------+---------------------+ | field01 | field02 | +---------+---------------------+ | NULL | Who thought of foo? | | NULL | Pooh thought of foo. | +---------+---------------------+ |
Query OK, 1 row affected (0.00 sec)
Quotes must go around text values.
Standard date format is "yyyy-mm-dd".
Standard time format is "hh:mm:ss".
Quotes are required around the standard date and time formats, noted above.
Dates may also be entered as "yyyymmdd" and times as "hhmmss".
If entered in this format, values don't need to be quoted.
Numeric values do not need to be quoted. This holds true regardless of the data type a column is formatted to contain (e.g. text, date, time, integer).
MySQL has a useful command buffer. The buffer stores the SQL statements you've entered thus far. Using it keeps you from having to retype the same commands over and over. Let's use this next step as an example.
Voilą!
+---------+-----------+------------------+------------+----------+ | field01 | field02 | field03 | field04 | field05 | +---------+-----------+------------------+------------+----------+ | 1 | first | NULL | NULL | NULL | | 2 | second | another | 1999-10-23 | 10:30:00 | | 3 | a third | more foo for you | 1999-10-24 | 10:30:01 | +---------+-----------+------------------+------------+----------+
It's in there!
Now, we're almost done...
Again, be careful with syntax. Quote marks need to go around text but not around numbers.
mysql 5.0.51b> update table01 set field03='new info' where field01=1;Query OK, 1 row affected (0.00 sec)
Remember to put commas between each field you're updating.
mysql 5.0.51b> update table01 set field04=19991022, field05=062218 where field01=1;Query OK, 1 row affected (0.00 sec)
+---------+-----------+------------------+------------+----------+ | field01 | field02 | field03 | field04 | field05 | +---------+-----------+------------------+------------+----------+ | 1 | first | new info | 1999-10-22 | 06:22:18 | | 2 | second | another | 1999-10-23 | 10:30:00 | | 3 | third one | more foo for you | 1999-10-24 | 10:30:01 | +---------+-----------+------------------+------------+----------+
Query OK, 3 rows affected (0.00 sec)
+---------+-----------+------------------+------------+----------+ | field01 | field02 | field03 | field04 | field05 | +---------+-----------+------------------+------------+----------+ | 1 | first | new info | 1999-10-22 | 15:29:01 | | 2 | second | another | 1999-10-23 | 15:29:01 | | 3 | third one | more foo for you | 1999-10-24 | 15:29:01 | +---------+-----------+------------------+------------+----------+
Wee haw!
Query OK, 1 row affected (0.01 sec)mysql 5.0.51b> select * from table01;
+---------+---------+----------+------------+----------+ | field01 | field02 | field03 | field04 | field05 | +---------+---------+----------+------------+----------+ | 1 | first | new info | 1999-10-22 | 15:29:01 | | 2 | second | another | 1999-10-23 | 15:29:01 | +---------+---------+----------+------------+----------+
Bye
Now you know some rudimentary commands for running a database in MySQL. Since MySQL is operated by executing SQL calls, you have a broad array of very powerful tools at your disposal. For instance, you're able to display data from several tables at once by joining related fields.
Similarly, SQL permits complex displays, updates or deletions of multiple records which fit specific criteria. So, your next step toward mastery is learning all about SQL.
James Hoffman has put a tutorial page up on the web entitled Introduction to Structured Query Language.
Another thing to note is MySQL offers good security features you'll need to use when operating on networks.
To learn more about MySQL and how to use it, the manual should be your first stop. Also, Paul DuBois' book, MySQL, comes highly recommended. In addition, the archives of the main list and the Win32 list are tremendous resources. The NYPHP user group has started a MySQL interest group you may find helpful.
If you're curious about database portability, you may find the Building Truly Portable Database Applications in PHP presentation interesting.
If you'll be developing hypertext interfaces to your databases using PHP, check out our SQL Solution™. It's a powerful, user friendly, platform independent API that will make your job a snap! Similarly, you might want to examine PEAR DB, a popular open source database abstraction layer (of which I'm the lead developer).
Also, if your scripts accept user input, the Form Solution™ is a handy tool for cleaning user input, generating HTML / XHTML compliant date/time form elements, validating and formatting date/time inputs and holding all variables submitted by a form. The result is improved security and data quality.