MySQL

81
-By V.Gouthaman.

description

Installation, Configuration, SetupBasic Querries.

Transcript of MySQL

Page 1: MySQL

-ByV.Gouthaman.

Page 2: MySQL

INTRODUCTIONMySQL is a relational database

management system (RDBMS) that runs as a server providing multi-user access to a number of databases.

The MySQL development project has made its source code available under the terms of the GNU General Public License, as well as under a variety of proprietary agreements. MySQL is owned and sponsored by a single for-profit firm, the Swedish company MySQL AB, now owned by Sun Microsystems, a subsidiary of Oracle Corporation.

Page 3: MySQL

Members of the MySQL community have created several forks such as Drizzle and MariaDB. Both forks were in progress before the Oracle acquisition (Drizzle was announced 8 months before the Sun acquisition).

Free-software projects that require a full-featured database management system often use MySQL. Such projects include (for example) WordPress, phpBB, Drupal and other software built on the LAMP software stack. MySQL is also used in many high-profile, large-scale World Wide Web products including Wikipedia, Google and Facebook.

Page 4: MySQL

INSTALLING MYSQL

Page 5: MySQL

Install MySQL 5.0 Community Edition on Windows

Step 1 :Download MySQL 5.0 Community Edition to your Desktop from

“http://dev.mysql.com/get/Downloads/MySQL-5.0/mysql-5.0.45-win32.zip/from/pick#mirrors”. Make sure you always download the “Complete

package “.

Page 6: MySQL

Step 2 :Unzip mysql-5.0.45-win32.zip (the downloaded mysql file) to get Setup.exe. Double click Setup.exe to start installing

MySQL. Click “Next ” when you are prompted as below.

Page 7: MySQL

Step 3 : Select “Typical” for Setup Type and click “Next ” again.

Page 8: MySQL

Step 4 : Click “Install ” to proceed with the installation process.

Page 9: MySQL

Step 5 : The setup activity will show you some advertisement. Read it if you wish and click

“Next “.

Page 10: MySQL

Step 6: Tick “Configure the MySQL Server now” and click “Next ” two times.

Page 11: MySQL
Page 12: MySQL

Step 7: Click “Standard Configuration” to ease installation process and click “Next ” again.

Page 13: MySQL

Step 8 : Tick “Install As Windows Service” to make MySQL auto-startup with Windows and “Include Bin Directory in

Windows PATH ” to make MySQL system files automatically available for other application.

Page 14: MySQL

Step 9 : Tick “Modify Security Settings” and enter a root (Administrator) password to secure your MySQL

installation. Don’t skip this step! Click “Next ” again.

Page 15: MySQL

Step 10 : Click “Execute” to start the MySQL Configuration process. Once finished, click

“Finish ” to end configuration.

Page 16: MySQL
Page 17: MySQL

Step 11: Make sure MySQL runs automatically after installation. You can check the status from

Administrative Tools Services snap in (Start -> Programs -> Administrative Tools -> Services ), also available via

Control Panel.

Page 18: MySQL

Step 12 : (OPTIONAL) Open your DOS command prompt (Run -> cud). Type in “net stat -na“. Check out ports opened by MySQL (3306) and Apache (80) . That

means the services are up and running.

Page 19: MySQL

Step 13 : (OPTIONAL) Run some of MySQL commands to further ensure that the installation is a success. Check out and follow the commands as pictured below. User account is root and password depends on what you have entered

previously during your MySQL configuration.

Page 20: MySQL

Step 14 : IMPORTANT:

Reboot your machine! This is to ensure all MySQL system files

are rss-read by Windows as environment variables.

Page 21: MySQL

QUERY COMMANDS

IN MYSQL

Page 22: MySQL

CREATE CommandThe Create command is used to create a table by specifying the tablename, fieldnames and constraints as shown below:

Syntax:

$createSQL=("CREATE TABLE tblName");

Example:

$createSQL=("CREATE TABLE tblstudent(fldstudid int(10) NOTNULL AUTO_INCREMENT PRIMARY KEY,fldstudName VARCHAR(250) NOTNULL,fldstudentmark int(4) DEFAULT '0' ");

Page 23: MySQL

SELECT CommandThe Select command is used to select the records from a table using its field names. To select all the fields in a table, '*' is used in the command. The result is assigned to a variable name as shown below:

Syntax:

$selectSQL=("SELECT field_names FROM tablename");

Example:

$selectSQL=("SELECT * FROM tblstudent");

Page 24: MySQL

DELETE Command

The Delete command is used to delete the records from a table using conditions as shown below:

Syntax:

$deleteSQL=("DELETE * FROM tablename WHERE condition");

Example:

$deleteSQL=("DELETE * FROM tblstudent WHERE fldstudid=2");

Page 25: MySQL

INSERT CommandThe Insert command is used to insert records into a table. The values are assigned to the field names as shown below:

Syntax:

$insertSQL=("INSERT INTO tblname(fieldname1,fieldname2..) VALUES(value1,value2,...) ");

Example:

$insertSQL=("INSERT INTO Tblstudent(fldstudName,fldstudmark)VALUES(Baskar,75) ");

Page 26: MySQL

UPDATE CommandThe Update command is used to update the field values using conditions. This is done using 'SET' and the fieldnames to assign new values to them.

Syntax:

$updateSQL=("UPDATE Tblname SET (fieldname1=value1,fieldname2=value2,...) WHERE fldstudid=IdNumber");

Example:

$updateSQL=("UPDATE Tblstudent SET (fldstudName=siva,fldstudmark=100) WHERE fldstudid=2");

Page 27: MySQL

DROP Command

The Drop command is used to delete all the records in a table using the table name as shown below:

Syntax:

$dropSQL=("DROP tblName");

Example:

$dropSQL=("DROP tblstudent");

Page 28: MySQL

Login to MySQL monitor

Syntax:

..\mysql\bin\mysql -u[username] -p[password]

Example:

..\mysql\bin\mysql -uroot -pmysecret

Page 29: MySQL

Create a database on the sql server.

Syntax:

CREATE {DATABASE | SCHEMA} [IF NOT EXISTS] db_name

[create_specification] ...

create_specification:

[DEFAULT] CHARACTER SET [=] charset_name

[DEFAULT] COLLATE [=] collation_name

Example:

u-1@srv-1 mysqlart $ mysql -u root

Welcome to the MySQL monitor. Commands end with ; or \g.

Your MySQL connection id is 5 to server version: 4.0.14-log

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

mysql> create database sysops;Query OK, 1 row affected (0.00

sec)mysql> quitByeu-1@srv-1 mysqlart $

Page 30: MySQL

Switch to a database.

mysql> use [db name];

Page 31: MySQL

mysql> show tables;

To see all the tables in the database

Page 32: MySQL

CREATE TABLESYNTAX: CREATE TABLE [table_name] (

[column_name1] INT AUTO_INCREMENT,

[column_name2] VARCHAR(30) NOT NULL,

[column_name3] ENUM('guest', 'customer', 'admin')NULL,

[column_name4] DATE NULL,

[column_name5] VARCHAR(30) NOT NULL,

[column_name6] DATETIME NOT NULL,

[column_name7] CHAR(1) NULL,

[column_name8] BLOB NULL,

[column_name9] TEXT NOT NULL,

UNIQUE(username),

PRIMARY KEY (column_name1)

Example:

CREATE TABLE user (

userid INT AUTO_INCREMENT,

username VARCHAR(30) NOT NULL,

group_type ENUM('guest', 'customer', 'admin') NULL,

date_of_birth DATE NULL,

password VARCHAR(30) NOT NULL,

registration_date DATETIME NOT NULL,

account_disable CHAR(1) NULL,

image BLOB NULL,

comment TEXT NOT NULL,

UNIQUE(username),

PRIMARY KEY (userid)

);

Page 33: MySQL

INSERT STATEMENTS

Syntax:

INSERT INTO table_name ( `col_A`, `col_B`, `col_C`) VALUES ( `col_A_data`, `col_B_data`, `col_C_data`) ;

Example:

INSERT INTO music ( 'id', `artist`, `album`) VALUES ( '1', `the beatles`, `Abbey Road`);

Page 34: MySQL

REPLACE STATEMENTS

Syntax:

REPLACE INTO table_name ( `col_A`, `col_B`) VALUES ( `col A data`, `col B data`) ;

Example:

REPLACE INTO music ( 'id', `artist`, `album`) VALUES ( '1', `the beatles`, `abbey road`);

Page 35: MySQL

UPDATE STATEMENTS

Syntax:

UPDATE table_name SET col_B='new_data' WHERE col_A='reference_data' ;

Example:

UPDATE music SET title='Come Together' WHERE id=1;

Page 36: MySQL

Add a new column "male" in table user.

Syntax:

ALTER TABLE [table_name]

ADD COLUMN [column_name]

CHAR(1) NOT NULL;

Example:

ALTER TABLE user

ADD COLUMN male

CHAR(1) NOT NULL;

Page 37: MySQL

Change column name "male" into "gender" in table user and change the type to VARCHAR(3)

and allow NULL values.

Syntax:

ALTER TABLE [table_name]

CHANGE [old_column] [new_column]

VARCHAR(3) NULL;

Example:

ALTER TABLE user

CHANGE male gender

VARCHAR (3) NULL;

Page 38: MySQL

Change the size of column "gender" from 3 to 6 in table user.

Syntax:

ALTER TABLE [table_name]

MODIFY [column_name] VARCHAR(6);

Example:

ALTER TABLE user

MODIFY gender VARCHAR(6);

Page 39: MySQL

SELECT STATEMENTS

Syntax:

SELECT * FROM table_name WHERE 1 ;

Example:

SELECT * FROM music WHERE 1;

Page 40: MySQL

DELETE STATEMENTS

Syntax:

DELETE FROM table_name WHERE column_name='search_data';

Example:

DELETE FROM music WHERE artist='the beatles';

Page 41: MySQL

Show field formats of the selected table.

Syntax:

DESCRIBE [table_name];

Example:

DESCRIBE mos_menu;

Page 42: MySQL

To see database's field formats.

mysql> describe [table name];

Page 43: MySQL

To delete a database.

Syntax:

mysql> drop database [database name];

Example:

DROP DATABASE demodb;

Page 44: MySQL

To delete a table.

mysql> drop table [table name];

Example:

DROP TABLE user;

Page 45: MySQL

Show all data in a table.

mysql> SELECT * FROM [table name];

Example:

SELECT *

FROM mos_menu;

Page 46: MySQL

Show all records from mos_menu table containing name "Home".

SELECT *

FROM [table_name]

WHERE [field_name]=[value];

Example:

SELECT *

FROM mos_menu

WHERE name = "Home";

Page 47: MySQL

Returns the columns and column information pertaining to the

designated table.

mysql> show columns from [table name];

Page 48: MySQL

Show certain selected rows with the value "whatever".

mysql> SELECT * FROM [table name] WHERE [field name] = "whatever";

Page 49: MySQL

Show all records containing the name "Bob" AND the phone

number '3444444'.

mysql> SELECT * FROM [table name] WHERE name = "Bob" AND phone_number = '3444444';

Page 50: MySQL

Show all records not containing the name "Bob" AND the phone

number '3444444' order by the phone_number field.

mysql> SELECT * FROM [table name] WHERE name != "Bob" AND phone_number = '3444444'

order by phone_number;

Page 51: MySQL

Show all records starting with the letters 'bob' AND the phone

number '3444444'.

mysql> SELECT * FROM [table name] WHERE name like "Bob%" AND phone_number =

'3444444';

Page 52: MySQL

Show all records starting with the letters 'bob' AND the phone number

'3444444' limit to records 1 through 5.

mysql> SELECT * FROM [table name] WHERE name like "Bob%" AND phone_number =

'3444444' limit 1,5;

Page 53: MySQL

Use a regular expression to find records. Use "REGEXP BINARY" to force

case-sensitivity. This finds any record beginning with a.

mysql> SELECT * FROM [table name] WHERE rec RLIKE "^a";

Page 54: MySQL

Show unique records.

mysql> SELECT DISTINCT [column name] FROM [table name];

Page 55: MySQL

Show selected records sorted in an ascending (asc) or descending (desc).

mysql> SELECT [col1],[col2] FROM [table name] ORDER BY [col2] DESC;

Page 56: MySQL

Return number of rows.

mysql> SELECT COUNT(*) FROM [table name];

Page 57: MySQL

Sum column.

mysql> SELECT SUM(*) FROM [table name];

Page 58: MySQL

Join tables on common columns.

mysql> select lookup.illustrationid, lookup.personid,person.birthday from lookup left

join person on lookup.personid=person.personid=statement to

join birthday in person table with primary illustration id;

Page 59: MySQL

Creating a new user. Login as root. Switch to the MySQL db. Make the

user. Update privs.

# mysql -u root -pmysql> use mysql;

mysql> INSERT INTO user (Host,User,Password) VALUES('%','username',PASSWORD('password'));

mysql> flush privileges;

Page 60: MySQL

Change a users password from unix shell.

# [mysql dir]/bin/mysqladmin -u username -h hostname.blah.org -p password 'new-password'

Page 61: MySQL

Change a users password from MySQL prompt. Login as root. Set the

password. Update privs.

# mysql -u root -pmysql> SET PASSWORD FOR 'user'@'hostname' =

PASSWORD('passwordhere');mysql> flush privileges;

Page 62: MySQL

Recover a MySQL root password. Stop the MySQL server process. Start again with no grant tables. Login to MySQL as root. Set new password. Exit

MySQL and restart MySQL server.

# /etc/init.d/mysql stop# mysqld_safe --skip-grant-tables &

# mysql -u rootmysql> use mysql;

mysql> update user set password=PASSWORD("newrootpassword") where User='root';

mysql> flush privileges;mysql> quit

# /etc/init.d/mysql stop# /etc/init.d/mysql start

Page 63: MySQL

Set a root password if there is on root password.

# mysqladmin -u root password newpassword

Page 64: MySQL

Update a root password.

# mysqladmin -u root -p oldpassword newpassword

Page 65: MySQL

Allow the user "bob" to connect to the server from localhost using the password

"passwd". Login as root. Switch to the MySQL db. Give privs. Update privs.

# mysql -u root -pmysql> use mysql;

mysql> grant usage on *.* to bob@localhost identified by 'passwd';

mysql> flush privileges;

Page 66: MySQL

Give user privilages for a db. Login as root. Switch to the MySQL db. Grant privs.

Update privs.

# mysql -u root -pmysql> use mysql;

mysql> INSERT INTO db (Host,Db,User,Select_priv,Insert_priv,Update_priv,Delete_priv,Create_p

riv,Drop_priv) VALUES ('%','databasename','username','Y','Y','Y','Y','Y','N');

mysql> flush privileges;

or

mysql> grant all privileges on databasename.* to username@localhost;mysql> flush privileges;

Page 67: MySQL

To update info already in a table.

mysql> UPDATE [table name] SET Select_priv = 'Y',Insert_priv = 'Y',Update_priv = 'Y' where [field

name] = 'user';

Page 68: MySQL

Delete a row(s) from a table.

mysql> DELETE from [table name] where [field name] = 'whatever';

Page 69: MySQL

Update database permissions/privilages.

mysql> flush privileges;

Page 70: MySQL

Delete a column.

mysql> alter table [table name] drop column [column name];

Page 71: MySQL

Add a new column to database.

mysql> alter table [table name] add column [new column name] varchar (20);

Page 72: MySQL

Change column name.

mysql> alter table [table name] change [old column name] [new column name] varchar (50);

Page 73: MySQL

Make a unique column so you get no dupes.

mysql> alter table [table name] add unique ([column name]);

Page 74: MySQL

Make a column bigger.

mysql> alter table [table name] modify [column name] VARCHAR(3);

Page 75: MySQL

Delete unique from table.

mysql> alter table [table name] drop index [colmn name];

Page 76: MySQL

Load a CSV file into a table.

mysql> LOAD DATA INFILE '/tmp/filename.csv' replace INTO TABLE [table name] FIELDS

TERMINATED BY ',' LINES TERMINATED BY '\n' (field1,field2,field3);

Page 77: MySQL

Dump all databases for backup. Backup file is sql commands to

recreate all db's.

# [mysql dir]/bin/mysqldump -u root -ppassword --opt >/tmp/alldatabases.sql

Page 78: MySQL

Dump one database for backup.

# [mysql dir]/bin/mysqldump -u username -ppassword --databases databasename

>/tmp/databasename.sql

Page 79: MySQL

Dump a table from a database.

# [mysql dir]/bin/mysqldump -c -u username -ppassword databasename tablename >

/tmp/databasename.tablename.sql

Page 80: MySQL

Restore database (or database table) from backup.

# [mysql dir]/bin/mysql -u username -ppassword databasename < /tmp/databasename.sql

Page 81: MySQL