[mysql] 기본명령어
MySQL를 접속하기 위해서는 셸 프롬프트에서 다음과 같이 입력합니다.
아래 접속예제는 root 사용자로 mysql 데이터베이스에 접속합니다. 초기에는 root 사용자에 패스워드가 설정되어 있지 않으므로 Enter password: 에 그냥 엔터를 입력합니다.
$ mysql -u root -p mysql
Enter password:
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 1 to server version: 3.23.49
Type 'help;' or '\h' for help. Type '\c' to clear the buffer.
mysql>
1. MySQL root 사용자에 패스워드 설정하기
root 사용자의 패스워드를 rootpasswd 로 설정합니다.
mysql> update user set password=password('rootpasswd') where user='root';
Querk OK, 2 rows affected (0.00 sec)
Rows matched : 2 Changed : 2 Warnings : 0
mysql> \q
변경된 root 사용자의 패스워드가 적용되기 위해서는 데이터베이스를 다시 불러와야 합니다.
$ mysqladmin -u root reload
변경된 root 사용자 패스워드로 다시 mysql에 접속해 보겠습니다.
Enter password: 에 변경된 패스워드인 rootpasswd 를 입력합니다.
$ mysql -u root -p mysql
Enter password:
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 1 to server version: 3.23.49
Type 'help;' or '\h' for help. Type '\c' to clear the buffer.
mysql>
2. 새로운 데이터베이스 생성하기
새로운 데이터베이스를 생성하기 위해 셸 프롬프트 상에서 다음과 같이 입력합니다.
생성할 데이터베이스 이름은 sample 입니다.
$ mysqladmin -u root -p create sample
Enter password:
Database "sample" created.
$
3. 데이터베이스 삭제하기
새롭게 생성된 sample 데이터베이스를 한 번 삭제해 보겠습니다.
$ mysqladmin -u root -p drop sample
Enter password:
Dropping the databases in potentially a very bad thing to do.
Any data stored in the database will be destroyed.
Do you really want to drop the 'sample' database [y/N]
y
Database "sample" dropped
$
4. 생성된 데이터베이스 등록하기
만일 sample 데이터베이스를 생성하였다면 이를 등록하여야 합니다. 등록하기 위해 mysql로 접속했다고 가정합니다.
mysql> insert into db values ('%','sample','test','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y');
Query OK, 1 row affected (0.00 sec)
위와 같이 sample 데이터베이스에 test계정을 사용자로 지정하였습니다.
5. 새로운 사용자(데이터베이스 소유자) 등록하기
위에서 지정한 test 계정을 등록하여야 합니다. 접속은 localhost로 가능하여 패스워드는 testpasswd 로 지정합니다.
mysql> insert into user (host,user,password) values ('localhost','test',password('testpasswd'));
Query OK, 1 row affected (0.00 sec)
6. sample 데이터베이스 백업하기
sample 데이터베이스를 백업해 보도록 하겠습니다. 셸 프롬트로에서 다음과 같이 입력합니다.
$ mysqldump -u root -p sample > sample_backup.sql
Enter password:
$
백업된 파일인 sample_backup.sql 파일을 볼 수 있을 것입니다.
7. sample 데이터베이스 복구하기
백업 받은 sample 데이터베이스를 복구해 보도록 하겠습니다. 셸 프롬트로에서 다음과 같이 입력합니다.
$ mysql -u root -p sample < sample_backup.sql
Enter password:
$
8. 모든 데이터베이스 백업하기
mysql의 모든 데이터베이스를 백업할 수 있습니다. 셸 프롬트로에서 다음과 같이 입력합니다.
$ mysqldump -a -u root -p > db_all_backup.sql
Enter password:
$
MySQL 기본 SQL 문법
새로운 데이터 베이스 생성하기
MySQL 안에서의 DB 생성
create database DB-name
프롬프트 상에서 mysqladmin 유틸리티를 사용한 DB 생성
#./mysqladmin create DB-name
기존의 데이터베이스 삭제하기
주의할 점은 먼저 데이터베이스 안에 모든 테이블을 삭제하고 데이터베이스를 삭제하여야 한다는 것입니다. 일단 삭제되면 다시는 복구할 수 없기 때문에 신중을 기해야 합니다.
MySQL 안에서의 DB삭제
drop database [IF EXISTS] DB-name
* 프롬프트 상에서 mysqladmin 유틸리티를 이용한 DB 생성
#./bin/mysqladmin drop DB-name
데이터베이스 안에 table 생성하기
일반적으로 데이터베이스를 생성해서 작업공간을 갖게 되면 실제로 데이터가 저장될 수 있는 table을 구성하게 되는데 create table의 문법은 다음과 같습니다(mySQL manual 페이지 참조)
CREATE [TEMPORARY] TABLE [IF NOT EXISTS] tbl_name [(create_definition,...)]
[table_options] [select_statement]
create_definition:
col_name type [NOT NULL | NULL] [DEFAULT default_value] [AUTO_INCREMENT] [PRIMARY KEY] [reference_definition]
or PRIMARY KEY (index_col_name,...)
or KEY [index_name] (index_col_name,...)
or INDEX [index_name] (index_col_name,...)
or UNIQUE [INDEX] [index_name] (index_col_name,...)
or [CONSTRAINT symbol] FOREIGN KEY index_name (index_col_name,...) [reference_definition]
or CHECK (expr)
type:
TINYINT[(length)] [UNSIGNED] [ZEROFILL]
or SMALLINT[(length)] [UNSIGNED] [ZEROFILL]
or MEDIUMINT[(length)] [UNSIGNED] [ZEROFILL]
or INT[(length)] [UNSIGNED] [ZEROFILL]
or INTEGER[(length)] [UNSIGNED] [ZEROFILL]
or BIGINT[(length)] [UNSIGNED] [ZEROFILL]
or REAL[(length,decimals)] [UNSIGNED] [ZEROFILL]
or DOUBLE[(length,decimals)] [UNSIGNED] [ZEROFILL]
or FLOAT[(length,decimals)] [UNSIGNED] [ZEROFILL]
or DECIMAL(length,decimals) [UNSIGNED] [ZEROFILL]
or NUMERIC(length,decimals) [UNSIGNED] [ZEROFILL]
or CHAR(length) [BINARY] or VARCHAR(length) [BINARY]
or DATE
or TIME
or TIMESTAMP
or DATETIME
or TINYBLOB
or BLOB
or MEDIUMBLOB
or LONGBLOB
or TINYTEXT
or TEXT
or MEDIUMTEXT
or LONGTEXT
or ENUM(value1,value2,value3,...)
or SET(value1,value2,value3,...)
index_col_name:
col_name [(length)]
reference_definition:
REFERENCES tbl_name [(index_col_name,...)]
create table 명령을 이용하여 테이블을 만들면 일반적으로 다음과 같은 디렉토리에 다음과 같은 확장자를 가진 파일이 만들어 집니다.
따라서 테이블을 만든다는 것은 다음의 세 개의 파일이 생성되는 것을 의미합니다.
#/usr/local/mysql/data/mysql/
테이블명.ISD 인덱스 파일구조를 나타내는 확장자
테이블명.ISM 실제의 데이터를 저장을 나타내는 확장자
테이블명.frm 테이블의 구조와 스키마를 저장하는 확장자
3.22 버전부터는 use database를 선택해서 해당 데이터베이스 안에서 테이블을 만들지 않고 데이터베이스 이름.테이블명 같이 데이터베이스와 테이블을 한번에 지정할 수 있습니다.
* 3.23 버전부터는 IF NOT EXISTS를 사용할 경우 같은 이름의 테이블이 존재하지 않을 때만 테이블이 생성됩니다. 그러나 이미 같은 이름의 테이블이 있더라도 에러는 발생하지 않습니다.
* 테이블을 만들 때 데이터의 default 값을 null, not null 등을 지정하지 않으면 기본적으로 null이 만들어집니다(기타 자세한 사항은 mysql dir 안에 있는 manual.txt 문서를 참조할 것).
만들어진 테이블의 구조를 변경하기
alter table은 데이터의 구조를 바꾸어 줍니다. 예를들어 컬럼을 늘리거나 삭제할 수 있고 인덱스를 없앨 수 있으며 컬럼의 타입을 바꾸거나, 컬럼의 이름을 바꿀 수 있습니다. 또한 테이블의 이름과 타입 등도 바꿀 수 있습니다.
ALTER [IGNORE] TABLE tbl_name alter_spec [, alter_spec ...]
alter_specification:
ADD [COLUMN] create_definition [FIRST | AFTER column_name ]
or ADD INDEX [index_name] (index_col_name,...)
or ADD PRIMARY KEY (index_col_name,...)
or ADD UNIQUE [index_name] (index_col_name,...)
or ALTER [COLUMN] col_name {SET DEFAULT literal | DROP DEFAULT}
or CHANGE [COLUMN] old_col_name create_definition
or MODIFY [COLUMN] create_definition
or DROP [COLUMN] col_name
or DROP PRIMARY KEY
or DROP INDEX index_name
or RENAME [AS] new_tbl_name
or table_options
(ex) mysql > alter table 기존테이블명 rename 바꿀테이블명; → 기존의 테이블명을 변경합니다.
mysql > alter table 테이블명 add index (인텍스줄컬럼), add primary key(주키를줄컬럼);
테이블 삭제하기
데이터베이스 안에 있는 테이블을 삭제합니다.
drop table [IF EXISTS] 테이블명 [, 테이블명2, ......]
위에서 보는 바와 같이 ,(컴마) 구분자를 이용하여 하나 이상의 테이블을 동시에 삭제 가능합니다.
3.22부터는 IF EXISTS 키워드를 사용하여 테이블이 존재하지 않을 경우에는 오류가 생기는 것을 방지할 수 있습니다.
[출처] [펌] mysql 기본명령어|작성자 인디고