Difference between revisions of "MySQL"

From WhyAskWhy.org Wiki
Jump to: navigation, search
m (Updated the row insert directions to list an example for multiple rows.)
m (Added example of showing tables/views for a database.)
Line 92: Line 92:
 
;
 
;
 
</syntaxhighlight>
 
</syntaxhighlight>
 +
 +
 +
== Display Tables or Views ==
 +
 +
* As of MySQL 5.0.1 the <syntaxhighlight lang="mysql" enclose="none">SHOW TABLES</syntaxhighlight> statement also displays <code>view</code> names.
 +
* As of MySQL 5.0.2 the (optional) <syntaxhighlight lang="mysql" enclose="none">FULL</syntaxhighlight> keyword may be given to display for each table whether the name refers to a <code>base table</code> or a <code>view</code>.
 +
 +
 +
<syntaxhighlight lang="mysql">
 +
SHOW FULL TABLES FROM my_test_db;
 +
</syntaxhighlight>
 +
 +
or
 +
 +
<syntaxhighlight lang="mysql">
 +
USE my_test_db;
 +
SHOW FULL TABLES;
 +
</syntaxhighlight>
 +
 +
 
== Create a user for that database with full privileges to it ==
 
== Create a user for that database with full privileges to it ==
  

Revision as of 23:38, 27 November 2014


Note: Examples shown here were tested on a range of MySQL versions from v5.1 to v5.5 with no regard to compatibility across versions.

Character length restrictions

[1] [2]

  • 64 characters for database name
  • 16 characters for user name
  •  ? characters for password length
    • seems to be dependent on the version
  • Field comments
    • 255 before before MySQL 5.5.3
    • 1024 after MySQL 5.5.3
  • Table comments
    • 60 characters before MySQL 5.5.3
    • 2048 characters after MySQL 5.5.3


Using comments in SQL files

[3]

These are all valid comment styles.

# Comment 1
-- Comment 2
/*
 
    Comment 3

*/


Create a database

[4]

CREATE DATABASE my_test_db CHARACTER SET utf8;


Create a table

[5]

Simple example

CREATE TABLE pet (
    name VARCHAR(20), 
    owner VARCHAR(20),
    species VARCHAR(20), 
    sex CHAR(1), 
    birth DATE, 
    death DATE
);

More complex example showing table and field comments

-- Holds per-user custom expiration settings for various IMAP mailboxes

CREATE TABLE `mailserver`.`mailbox_custom_expiration_settings` 
(
  `id` int(11) NOT NULL auto_increment,
  `user_id` int(11) NOT NULL
    COMMENT "The virtual user id",
  `imap_mailbox_name` text NOT NULL 
    COMMENT "Examples: Newsletters, Trash, Spam, Facebook, Cuteoverload",
  `imap_search_key` varchar(20) NOT NULL DEFAULT 'SAVEDBEFORE'
    COMMENT "BEFORE or SAVEDBEFORE are supported choices",
  `date_specification_interval` VARCHAR(20) NOT NULL
    COMMENT "Should be set to a period shorter than the default to be effective",
  `last_modified` timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  `comments` text,
  PRIMARY KEY (`id`),
  -- Nuke the matching row from this table that corresponds to the virtual user id
  FOREIGN KEY (`user_id`) REFERENCES virtual_users(`id`) ON DELETE CASCADE 
) 
    ENGINE=InnoDB 
    DEFAULT CHARSET=utf8
    COMMENT="Controls (optional) per-user expiration times for mail content"
;


Display Tables or Views

  • As of MySQL 5.0.1 the SHOW TABLES statement also displays view names.
  • As of MySQL 5.0.2 the (optional) FULL keyword may be given to display for each table whether the name refers to a base table or a view.


SHOW FULL TABLES FROM my_test_db;

or

USE my_test_db;
SHOW FULL TABLES;


Create a user for that database with full privileges to it

Depending on your needs, you'll setup the user in one of several ways.

Database server is on the same box as the application

Connecting via a UNIX socket

CREATE USER 'my_test_db_usr'@'localhost' IDENTIFIED BY 'INITIAL_PASSWORD';
GRANT ALL PRIVILEGES ON my_test_db.* TO 'my_test_db_usr'@'localhost';

Connecting via a TCP socket

Useful if the application is running inside of a chroot jail for instance

CREATE USER 'my_test_db_usr'@'127.0.0.1' IDENTIFIED BY 'INITIAL_PASSWORD';
GRANT ALL PRIVILEGES ON my_test_db.* TO 'my_test_db_usr'@'127.0.0.1';


Application is on a remote server

Remote host is specified via IP Address

CREATE USER 'my_test_db_usr'@'192.168.1.105' IDENTIFIED BY 'INITIAL_PASSWORD';
GRANT ALL PRIVILEGES ON my_test_db.* TO 'my_test_db_usr'@'192.168.1.105';

Remote host is specified by hostname

Valid DNS A record or /etc/hosts entry

CREATE USER 'my_test_db_usr'@'webserver1.example.org' IDENTIFIED BY 'INITIAL_PASSWORD';
GRANT ALL PRIVILEGES ON my_test_db.* TO 'my_test_db_usr'@'webserver1.example.org';


Update user account to allow connecting from a different host

[6]

If you created your MySQL user account and limited it to connections from a specific IP Address, at some point you'll need to create another account or update the host it is allowed to be used from (my choice) if the remote IP changes. One example would be moving the application server from one VLAN to another. In our example 192.168.2.25 is the new IP and the old IP was 192.168.1.105.

UPDATE user set Host = '192.168.2.25' WHERE User = 'my_test_db_usr' AND Host = '192.168.1.105';
FLUSH PRIVILEGES;

It's important to note however that you'll need to reapply database permissions for the affected user account however. What we've done so far has only adjusted the login or USAGE permission.

Reset password for user account

SET PASSWORD for 'my_test_db_usr'@'localhost' = PASSWORD('REAL_PASSWORD_HERE');


Viewing the account you're logged in as (equivalent of UNIX whoami)

[7]

SELECT USER(),CURRENT_USER();
  • USER() reports how you attempted to authenticate in MySQL
  • CURRENT_USER() reports how you were allowed to authenticate in MySQL

RolandoMySQLDBA notes: Sometimes, they are different


Import or run SQL statements from file

source my-sql-file.sql;


Rename table

RENAME TABLE `my_test_db`.`table_name` TO `my_test_db`.`my_new_table_name`;


Alter table

[8] [9]

Insert new field

ALTER TABLE contacts ADD email VARCHAR(60);


Insert new field at specific location

ALTER TABLE contacts ADD email VARCHAR(60) AFTER name;
ALTER TABLE contacts ADD email VARCHAR(60) FIRST;


Inserting new rows

[10]

Note: For fields that have default values, you can skip including those field names and values in the INSERT INTO and VALUES statements if you wish to use the defaults.

A single row

INSERT INTO table_name (
  `field_name1`, 
  `field_name2`, 
  `field_name3`
)
VALUES (
  'Value1', 
  'Value2', 
  'Value3'
);


Multiple rows

INSERT INTO table_name (
  `field_name1`, 
  `field_name2`, 
  `field_name3`
)
VALUES 
  ('Value1', 'Value2', 'Value3'),
  ('Value1', 'Value2', 'Value3'),
  ('Value1', 'Value2', 'Value3'),
  ('Value1', 'Value2', 'Value3'),
  ('Value1', 'Value2', 'Value3'),
  ('Value1', 'Value2', 'Value3')
;

Pay careful attention to the lack of a trailing comma for the last row we are inserting. I often forget and include it and have to remove it after MySQL complains.

Update field

[10]

UPDATE table_name SET table_field = 'Value' WHERE id = '1';


Delete row

DELETE FROM virtual_domains WHERE id = '1' OR id = '7';


Delete user account

DROP USER 'my_test_db_usr'@'localhost';


Delete database

DROP DATABASE 'my_test_db';


Resetting the root user account

[11] [12]

More Secure

1 nano /home/me/FILE
2 # Add SQL statement from section below
3 # Save & quit nano
4 sudo /etc/init.d/mysql stop
5 mysqld_safe --init-file=/home/me/FILE &
6 rm /home/me/FILE
7 sudo /etc/init.d/mysql restart

Less secure

1 sudo /etc/init.d/mysql stop
2 sudo mysqld --skip-grant-tables &
3 mysql -u root mysql
4 UPDATE user SET Password=PASSWORD('YOURNEWPASSWORD') WHERE User='root'; FLUSH PRIVILEGES; exit;


Viewing privileges granted to a user

[13] [14]

  • select * from mysql.user;
    
    • Parse results by eye (not pretty)
  • SHOW GRANTS FOR username@ipaddress;
    
  • SHOW GRANTS;
    
    • For current user


Show the character set for a database

[15]

SHOW CREATE DATABASE database_name;


Show the database engine type

[16]

USE DATABASE database_name;
SHOW CREATE TABLE table_name;


MySQL config/option file search order

The MySQL configuration file (referred to as an option file) can be located in multiple places, but the order of precedence determines which configuration file will be used when you do not explicitly specify a file.

Unix, Linux and Mac OS X MySQL option file search order
File Name Purpose
/etc/my.cnf Global options
/etc/mysql/my.cnf Global options
SYSCONFDIR/my.cnf Global options
$MYSQL_HOME/my.cnf Server-specific options
defaults-extra-file The file specified with --defaults-extra-file=path, if any
~/.my.cnf User-specific options

As mentioned on the Using Option Files [17] reference page running mysql with the --help option will show you the preconfigured locations that MySQL will search for the options file.

Example:

$ mysql --help --verbose  | grep -A 1 'Default options'
Default options are read from the following files in the given order:
/etc/my.cnf /etc/mysql/my.cnf /usr/etc/my.cnf ~/.my.cnf

Important

  • On Unix platforms, MySQL ignores configuration files that are world-writable. This is intentional as a security measure.
  • MySQL looks for option files in the order listed in the table reads any that exist. If multiple instances of a given option are found, the last instance takes precedence.
    • Exception: For mysqld, the first instance of the --user option is used as a security precaution, to prevent a user specified in an option file from being overridden on the command line.


Path variables

  • ~ represents the current user's home directory (the value of $HOME).
  • SYSCONFDIR represents the directory specified with the SYSCONFDIR option to CMake when MySQL was built. By default, this is the etc directory located under the compiled-in installation directory.
  • MYSQL_HOME is an environment variable containing the path to the directory in which the server-specific my.cnf file resides. If MYSQL_HOME is not set and you start the server using the mysqld_safe program, mysqld_safe attempts to set MYSQL_HOME as follows:
    • Let BASEDIR and DATADIR represent the path names of the MySQL base directory and data directory, respectively.
    • If there is a my.cnf file in DATADIR but not in BASEDIR, mysqld_safe sets MYSQL_HOME to DATADIR.
    • Otherwise, if MYSQL_HOME is not set and there is no my.cnf file in DATADIR, mysqld_safe sets MYSQL_HOME to BASEDIR.

In MySQL 5.5, use of DATADIR as the location for my.cnf is deprecated.

Typically, DATADIR is /usr/local/mysql/data for a binary installation or /usr/local/var for a source installation. Note that this is the data directory location that was specified at configuration time, not the one specified with the --datadir option when mysqld starts. Use of --datadir at runtime has no effect on where the server looks for option files, because it looks for them before processing any options.

Any long option that may be given on the command line when running a MySQL program can be given in an option file as well. To get the list of available options for a program, run it with the --help option.

References