Sunteți pe pagina 1din 11

MySQL

Introducere MySQL este un sistem de gestiune a bazelor de date rela ional, produs de compania suedez MySQL AB i distribuit sub Licen a Public General GNU. Este cel mai popular SGBD open-source la ora actual, fiind o component cheie a stivei LAMP (Linux, Apache, MySQL, PHP). Dei este folosit foarte des mpreun cu limbajul de programare PHP, cu MySQL se pot construi aplica ii n orice limbaj major. Exist multe scheme API disponibile pentru MySQL ce permit scrierea aplica iilor n numeroase limbaje de programare pentru accesarea bazelor de date MySQL, cum are fi: C, C++, C#, Borland Delphi, Java, Perl, PHP, Python, FreeBasic, etc., fiecare dintre acestea folosind un tip spefic API. O interfa de tip ODBC denumit MyODBC permite altor limbaje de programare ce folosesc aceast interfa , s interac ioneze cu bazele de date MySQL cum ar fi ASP sau Visual Basic. n sprijinul acestor limbaje de programare, unele companii produc componente de tip COM/COM+ sau .NET (pentru Windows) prin intermediul crora respectivele limbaje s poat folosi acest SGBD mult mai uor dect prin intermediul sistemului ODBC. Aceste componente pot fi gratuite (ca de exemplu MyVBQL) sau comerciale. Licen a GNU GPL nu permite ncorporarea MySQL n softuri comerciale; cei care doresc s fac acest lucru pot achizi iona, contra cost, o licen comercial de la compania productoare, MySQL AB. MySQL este component integrat a platformelor LAMP sau WAMP (Linux/WindowsApache-MySQL-PHP/Perl/Python). Popularitatea sa ca aplica ie web este strns legat de cea a PHP-ului care este adesea combinat cu MySQL i denumit Duo-ul Dinamic. n multe cr i de specialitate este precizat faptul ca MySQL este mult mai uor de inv at i folosit dect multe din aplica iile de gestiune a bazelor de date, ca exemplu comanda de ieire fiind una simpl i evident: exit sau quit. Pentru a administra bazele de date MySQL se poate folosi modul linie de comand sau, prin descrcare de pe internet, o interfa grafic: MySQL Administrator i MySQL Query Browser. Un alt instrument de management al acestor baze de date este aplica ia gratuit, scris n PHP, phpMyAdmin. MySQL poate fi rulat pe multe dintre platformele software existente: AIX, FreeBSD, GNU/Linux, Mac OS X, NetBSD, Solaris, SunOS, Windows 9x/NT/2000/XP/Vista. Tipuri de date in MySQL

TIP

NUME

INTERVAL VALORI -128 ,127 [0,255 pentru UNSIGNED]

ATRIBUTE AUTO_INCREMENT UNSIGNED, ZEROFILL, SERIAL DEFAULT VALUE

Numeric {1 byte}

TINYINT[(M)]

Numeric {2 bytes} Numeric {3 bytes} Numeric {4 bytes} Numeric {8 bytes} Numeric {4 or 8} Numeric {4 bytes} Numeric {8 bytes} Numeric {M+2} Bit {8 bytes}

SMALLINT[(M)]

-32,768, 32,767 [0, 65,535]

AUTO_INCREMENT, UNSIGNED, ZEROFILL, SERIAL DEFAULT VALUE AUTO_INCREMENT, UNSIGNED, ZEROFILL, SERIAL DEFAULT VALUE AUTO_INCREMENT, UNSIGNED, ZEROFILL, SERIAL DEFAULT VALUE AUTO_INCREMENT, UNSIGNED, ZEROFILL, SERIAL DEFAULT VALUE UNSIGNED, ZEROFILL UNSIGNED, ZEROFILL UNSIGNED, ZEROFILL

-8,388,608 to 8,388,607 MEDIUMINT[(M)] [0 ,16,777,215] INT[(M)] -/+2.147E+9 [0, 4.294E+9] -/+9.223E+18 [0,18.45E+18] p=0-24 --> "FLOAT" p=25-53 --> "DOUBLE" Min=+/-1.175E-38 Max=+/-3.403E+38 Min=+/-2.225E-308 Max=+/-1.798E+308

BIGINT[(M)] FLOAT(p) FLOAT[(M,D)] DOUBLE[(M,D)]

Max Range = DOUBLE DECIMAL[(M,[D])] range Stored as string Fixed point vs. DOUBLE float BIT[(M)]

UNSIGNED, ZEROFILL

Binary. Display by [add zero Prior to 5.03 |converting with BIN()]. TINYINT(1) Synonym M=1-64 M=0-255 Characters, FIXED. Right padded with spaces. M=0-65,535 Characters M=0-255 <v5.0.3 0-255 Characters 0-65,535 Char's 0-16,777,215 Char's 0-4,294,967,295 Char's M=0-255 bytes, FIXED. BINARY, CHARACTER SET BINARY, CHARACTER SET BINARY, CHARACTER SET BINARY, CHARACTER SET BINARY, CHARACTER SET BINARY, CHARACTER SET Global Only (case sensitive)

String CHAR[(M)] {M char's} String {M char's1} VARCHAR(M)

String TINYTEXT2 1 {#char's } String TEXT2 1 {#char's } String MEDIUMTEXT2 1 {#char's } String LONGTEXT2 {#char's1} String BINARY[(M)] {M bytes}

String VARBINARY(M) {M bytes} String TINYBLOB {#bytes1} String BLOB {#bytes1} String MEDIUMBLOB {#bytes1} String LONGBLOB {#bytes1} String {1-2 bytes} String {1-8 bytes} Date & Time {3 bytes} Date & Time {8 bytes} Date & Time {3 bytes} Date & Time {4 bytes} Date & Time {1 bytes} ENUM2 ("A1","A2",...) SET2 ("A1","A2",...) DATE

0-65,535 bytes M=0-255 <v5.0.3 0-255 bytes 0-65,535 bytes 0-16,777,215 bytes 0-4,294,967,295 bytes Column is exactly 1 of 165,535 values Column is 0 or more values in list of 1-64 members "1000-01-01" - "9999-1231" "1000-01-01 00:00:00" "9999-12-31 23:59:59" "-838:59:59" - "838:59:59" 19700101000000 2037+ 1900 - 2155

Global Only (case sensitive) Global Only (case sensitive) Global Only (case sensitive) Global Only (case sensitive) Global Only (case sensitive) CHARACTER SET

CHARACTER SET Global Only (YYYY-MM-DD) Global Only (YYYY-MM-DD hh:mm:ss) Global Only (hh:mm:ss) Global Only (YYYYMMDDhhmmss) Global Only (YYYY)

DATETIME

TIME

TIMESTAMP

YEAR

Comenzi MySQL comenzile MySQL pot fi scrise pe unul sau mai multe rnduri i se termina cu ;. 1. CREARE DATABASE pentru crearea unei noi baze de date CREATE {DATABASE | SCHEMA} [IF NOT EXISTS] db_name [create_specification ...] create_specification: [DEFAULT] CHARACTER SET charset_name

| [DEFAULT] COLLATE collation_name Ex.: CREATE DATABASE mydb; 2. DROP DATABASE pentru tergerea unei baze de date DROP {DATABASE | SCHEMA} [IF EXISTS] db_name Ex.: DROP DATABASE mydb; 3. SHOW DATABASES afieaz toate bazele de date de pe server. 4. USE schimbarea bazei de date USE db_name Ex.: USE mydb; 5. SHOW TABLES afieaz toate tabelele din baza de date curent 6. CREATE TABLE pentru crearea unei noi tabele
CREATE [TEMPORARY] TABLE [IF NOT EXISTS] tbl_name { LIKE old_tbl_name | (LIKE old_tbl_name) }

create_definition: col_name column_definition | [CONSTRAINT [symbol]] PRIMARY KEY [index_type] (index_col_name,...) | {INDEX|KEY} [index_name] [index_type] (index_col_name,...) | [CONSTRAINT [symbol]] UNIQUE [INDEX|KEY] [index_name] [index_type] (index_col_name,...) | {FULLTEXT|SPATIAL} [INDEX|KEY] [index_name] (index_col_name,...) | [CONSTRAINT [symbol]] FOREIGN KEY [index_name] (index_col_name,...) reference_definition | CHECK (expr) column_definition: data_type [NOT NULL | NULL] [DEFAULT default_value]
[AUTO_INCREMENT] [UNIQUE [KEY] | [PRIMARY] KEY] [COMMENT 'string'] [reference_definition]

data_type: BIT[(length)] | TINYINT[(length)] [UNSIGNED] [ZEROFILL] | SMALLINT[(length)] [UNSIGNED] [ZEROFILL] | MEDIUMINT[(length)] [UNSIGNED] [ZEROFILL] | INT[(length)] [UNSIGNED] [ZEROFILL] | INTEGER[(length)] [UNSIGNED] [ZEROFILL] | BIGINT[(length)] [UNSIGNED] [ZEROFILL] | REAL[(length,decimals)] [UNSIGNED] [ZEROFILL] | DOUBLE[(length,decimals)] [UNSIGNED] [ZEROFILL] | FLOAT[(length,decimals)] [UNSIGNED] [ZEROFILL] | DECIMAL(length,decimals) [UNSIGNED] [ZEROFILL] | NUMERIC(length,decimals) [UNSIGNED] [ZEROFILL]

| | | | | | | | | | | | | | | | | | |

DATE TIME TIMESTAMP DATETIME YEAR CHAR(length) [CHARACTER SET charset_name] [COLLATE VARCHAR(length) [CHARACTER SET charset_name] [COLLATE BINARY(length) VARBINARY(length) TINYBLOB BLOB MEDIUMBLOB LONGBLOB TINYTEXT [BINARY] [CHARACTER SET charset_name] [COLLATE TEXT [BINARY] [CHARACTER SET charset_name] [COLLATE MEDIUMTEXT [BINARY] [CHARACTER SET charset_name] [COLLATE LONGTEXT [BINARY] [CHARACTER SET charset_name] [COLLATE ENUM(value1,value2,value3,...) [CHARACTER SET charset_name] [COLLATE SET(value1,value2,value3,...) [CHARACTER SET charset_name] [COLLATE

collation_name] collation_name]

collation_name] collation_name] collation_name] collation_name] collation_name] collation_name]

| spatial_type

index_col_name: col_name [(length)] [ASC | DESC] index_type:


USING {BTREE | HASH | RTREE}

reference_definition: REFERENCES tbl_name [(index_col_name,...)]


[MATCH FULL | MATCH PARTIAL | MATCH SIMPLE] [ON DELETE reference_option] [ON UPDATE reference_option]

reference_option:
RESTRICT | CASCADE | SET NULL | NO ACTION

table_option:
| | | | | | | | {ENGINE|TYPE} [=] engine_name AUTO_INCREMENT [=] value AVG_ROW_LENGTH [=] value [DEFAULT] CHARACTER SET charset_name CHECKSUM [=] {0 | 1} COLLATE collation_name COMMENT [=] 'string' CONNECTION [=] 'connect_string' DATA DIRECTORY [=] 'absolute path to directory'

| | | | | | | | |

DELAY_KEY_WRITE [=] {0 | 1} INDEX DIRECTORY [=] 'absolute path to directory' INSERT_METHOD [=] { NO | FIRST | LAST } MAX_ROWS [=] value MIN_ROWS [=] value PACK_KEYS [=] {0 | 1 | DEFAULT} PASSWORD [=] 'string' ROW_FORMAT [=] {DEFAULT|DYNAMIC|FIXED|COMPRESSED|REDUNDANT|COMPACT} UNION [=] (tbl_name[,tbl_name]...)

select_statement:
[IGNORE | REPLACE] [AS] SELECT ... (Some legal select

statement)

Ex.: CREATE TABLE example1 ( id INT, data VARCHAR(100) ); CREATE TABLE STUDENTI ( nrmat INT, nume VARCHAR(200), datanasterii DATE, specializarea VARCHAR(100), anstudiu INT, grupa VARCHAR(10) ); 7. DROP TABLE pentru tergerea unei tabele DROP [TEMPORARY] TABLE [IF EXISTS] tbl_name [, tbl_name] ... [RESTRICT | CASCADE] Ex.: DROP TABLE STUDENTI; 8. ALTER TABLE modificarea structurii unei tabele dintr-o baz de date MySQL ALTER [IGNORE] TABLE tbl_name alter_specification [, alter_specification] ... alter_specification: table_option ... | ADD [COLUMN] col_name column_definition [FIRST | AFTER col_name ] | ADD [COLUMN] (col_name column_definition,...) | ADD {INDEX|KEY} [index_name] [index_type] (index_col_name,...) | ADD [CONSTRAINT [symbol]] PRIMARY KEY [index_type] (index_col_name,...) | ADD [CONSTRAINT [symbol]] UNIQUE [INDEX|KEY] [index_name] [index_type] (index_col_name,...)

| ADD [FULLTEXT|SPATIAL] [INDEX|KEY] [index_name] (index_col_name,...) | ADD [CONSTRAINT [symbol]] FOREIGN KEY [index_name] (index_col_name,...) reference_definition | ALTER [COLUMN] col_name {SET DEFAULT literal | DROP DEFAULT} | CHANGE [COLUMN] old_col_name new_col_name column_definition [FIRST|AFTER col_name] | MODIFY [COLUMN] col_name column_definition [FIRST | AFTER col_name] | DROP [COLUMN] col_name | DROP PRIMARY KEY | DROP {INDEX|KEY} index_name | DROP FOREIGN KEY fk_symbol | DISABLE KEYS | ENABLE KEYS | RENAME [TO] new_tbl_name | ORDER BY col_name [, col_name] ... | CONVERT TO CHARACTER SET charset_name [COLLATE collation_name] | [DEFAULT] CHARACTER SET charset_name [COLLATE collation_name] | DISCARD TABLESPACE | IMPORT TABLESPACE index_col_name: col_name [(length)] [ASC | DESC] index_type: USING {BTREE | HASH | RTREE} Ex.: ALTER TABLE STUDENTI ADD COLUMN media_generala float; 9. DESCRIBE pentru afiarea detaliata a informa iilor referitoare la cmpurile unei tabele MySQL {DESCRIBE | DESC} tbl_name [col_name | wild] Ex.: DESCRIBE STUDENTI;
+---------------+--------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +---------------+--------------+------+-----+---------+-------+ | nrmat | int(11) | YES | | NULL | | | nume | varchar(200) | YES | | NULL | | | datanasterii | date | YES | | NULL | | | specializarea | varchar(100) | YES | | NULL | | | anstudiu | int(11) | YES | | NULL | | | grupa | varchar(10) | YES | | NULL | | +---------------+--------------+------+-----+---------+-------+ 6 rows in set (0.00 sec)

10. SHOW COLUMNS pentru afiarea detaliata a informa iilor referitoare la cmpurile unei tabele MySQL SHOW [FULL] COLUMNS FROM tbl_name [FROM db_name] [LIKE 'pattern' | WHERE expr]

Ex.: SHOW COLUMNS FROM STUDENTI; 11. INSERT INTO pentru adugarea unei noi nregistrri ntr-o tabel MySQL INSERT [LOW_PRIORITY | DELAYED | HIGH_PRIORITY] [IGNORE] [INTO] tbl_name [(col_name,...)] VALUES ({expr | DEFAULT},...),(...),... [ ON DUPLICATE KEY UPDATE col_name=expr, ... ] sau INSERT [LOW_PRIORITY | DELAYED | HIGH_PRIORITY] [IGNORE] [INTO] tbl_name SET col_name={expr | DEFAULT}, ... [ ON DUPLICATE KEY UPDATE col_name=expr, ... ] sau INSERT [LOW_PRIORITY | HIGH_PRIORITY] [IGNORE] [INTO] tbl_name [(col_name,...)] SELECT ... [ ON DUPLICATE KEY UPDATE col_name=expr, ... ] Ex.: INSERT INTO STUDENTI Tudor','1977/9/7','Calculatoare',1,'1121a'); INSERT INTO STUDENTI Mihai','1977/1/2','Calculatoare',1,'1121a'); INSERT INTO STUDENTI Andrei','1978/1/2','Calculatoare',1,'1121a'); INSERT INTO STUDENTI Ion','1977/3/1','Calculatoare',1,'1121b');

VALUES(1,'Cerlinca VALUES(2,'Petriuc VALUES(3,'Petrea VALUES(4,'Ionescu

12. UPDATE pentru actualizarea con inutului unei tabele MySQL UPDATE [LOW_PRIORITY] [IGNORE] tbl_name SET col_name1=expr1 [, col_name2=expr2 ...] [WHERE where_condition] [ORDER BY ...] [LIMIT row_count] Ex.:UPDATE STUDENTI SET nume='Cerlinca Tudor Ioan' where nrmat=1; 13. DELETE pentru tergerea unor nregistrri dintr-o tabel MySQL DELETE [LOW_PRIORITY] [QUICK] [IGNORE] FROM tbl_name [WHERE where_condition] [ORDER BY ...] [LIMIT row_count] Ex.:

DELETE FROM STUDENTI where nrmat=1; 14. SELECT pentru afiarea informa iilor con inute n tabelele unei baze de date SELECT [ALL | DISTINCT | DISTINCTROW ] [HIGH_PRIORITY] [STRAIGHT_JOIN] [SQL_SMALL_RESULT] [SQL_BIG_RESULT] [SQL_BUFFER_RESULT] [SQL_CACHE | SQL_NO_CACHE] [SQL_CALC_FOUND_ROWS] select_expr, ... [FROM table_references [WHERE where_condition] [GROUP BY {col_name | expr | position} [ASC | DESC], ... [WITH ROLLUP]] [HAVING where_condition] [ORDER BY {col_name | expr | position} [ASC | DESC], ...] [LIMIT {[offset,] row_count | row_count OFFSET offset}] [PROCEDURE procedure_name(argument_list)] [INTO OUTFILE 'file_name' export_options | INTO DUMPFILE 'file_name' | INTO @var_name [, @var_name]] [FOR UPDATE | LOCK IN SHARE MODE]] Ex.: SELECT * FROM STUDENTI;
+-------+----------------+--------------+---------------+----------+-------+ | nrmat | nume | datanasterii | specializarea | anstudiu | grupa | +-------+----------------+--------------+---------------+----------+-------+ | 2 | Petriuc Mihai | 1977-01-02 | Calculatoare | 1 | 1121a | | 1 | Cerlinca Tudor | 1977-09-07 | Calculatoare | 1 | 1121a | | 3 | Petrea Andrei | 1978-01-02 | Calculatoare | 1 | 1121a | | 4 | Ionescu Ion | 1977-03-01 | Calculatoare | 1 | 1121b | +-------+----------------+--------------+---------------+----------+-------+

4 rows in set (0.00 sec)

SELECT * FROM STUDENTI ORDER BY datanasterii;


+-------+----------------+--------------+---------------+----------+-------+ | nrmat | nume | datanasterii | specializarea | anstudiu | grupa | +-------+----------------+--------------+---------------+----------+-------+ | 2 | Petriuc Mihai | 1977-01-02 | Calculatoare | 1 | 1121a | | 4 | Ionescu Ion | 1977-03-01 | Calculatoare | 1 | 1121b | | 1 | Cerlinca Tudor | 1977-09-07 | Calculatoare | 1 | 1121a | | 3 | Petrea Andrei | 1978-01-02 | Calculatoare | 1 | 1121a | +-------+----------------+--------------+---------------+----------+-------+ 4 rows in set (0.00 sec)

SELECT * FROM STUDENTI WHERE grupa=1121a


+-------+----------------+--------------+---------------+----------+-------+ | nrmat | nume | datanasterii | specializarea | anstudiu | grupa | +-------+----------------+--------------+---------------+----------+-------+ | 2 | Petriuc Mihai | 1977-01-02 | Calculatoare | 1 | 1121a | | 1 | Cerlinca Tudor | 1977-09-07 | Calculatoare | 1 | 1121a | | 3 | Petrea Andrei | 1978-01-02 | Calculatoare | 1 | 1121a |

+-------+----------------+--------------+---------------+----------+-------+ 3 rows in set (0.00 sec)

SELECT * FROM STUDENTI WHERE nume LIKE Pe%;


+-------+---------------+--------------+---------------+----------+-------+ | nrmat | nume | datanasterii | specializarea | anstudiu | grupa | +-------+---------------+--------------+---------------+----------+-------+ | 2 | Petriuc Mihai | 1977-01-02 | Calculatoare | 1 | 1121a | | 3 | Petrea Andrei | 1978-01-02 | Calculatoare | 1 | 1121a | +-------+---------------+--------------+---------------+----------+-------+ 2 rows in set (0.00 sec)

SELECT COUNT(*) as 'NrStudentiGrupa', grupa from STUDENTI GROUP BY grupa ORDER BY NrStudentiGrupa;
+-----------------+-------+ | NrStudentiGrupa | grupa | +-----------------+-------+ | 1 | 1121b | | 3 | 1121a | +-----------------+-------+ 2 rows in set (0.00 sec)

SELECT COUNT(*) as 'NrStudentiGrupa', grupa from STUDENTI GROUP BY grupa HAVING NrStudentiGrupa>1 ORDER BY NrStudentiGrupa;
+-----------------+-------+ | NrStudentiGrupa | grupa | +-----------------+-------+ | 1 | 1121b | | 3 | 1121a | +-----------------+-------+ 2 rows in set (0.00 sec)

Tema:
1. Veti crea urmtoarele tabele: autori si carti autori: idautor numar intreg nume sir de caractere carti: idcarte numar intreg titlul sir de caractere idautor numar intreg pret numar intreg 2. Veti introduce date in cele doua tabele Tabela AUTORI 1 Liviu Rebreanu 2 Marin Preda 3 Ion Creanga Tabela CARTI 1 Padurea Spanzuratilor 1

23

2 3 4 5

Ion Morometii Amintiri din copilarie Capra cu trei iezi

1 2 3 3

40 15 100 75

3.Veti realiza urmatoarele interogari: a) listarea continutului tabelei autori b) listarea continutului tabelei carti c) afisarea autorilor al caror nume incepe cu litera L d) afisarea cartilor cu pretul mai mare decat o valoare de referinta (stablita de catre utilizator) e) afisarea cartilor scrise de un anumit autor f) afisarea cartilor sub urmatoarea forma: Titlu Autor Pret Padurea Spanzuratilor Liviu Rebreanu 23 Ion Liviu Rebreanu 40 --------------------------------------------------------------------------