MySQL Cheatsheet

JunePyo Suh·2020년 5월 23일
0

Installing MySQL on Mac

brew install mysql

If HomeBrew package manager is uninstalled:

`$ /usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"`

MySQL Initial Settings

mysql.server start
mysql_secure_installation

After this step, a series of questions will follow to help with initialization.

Would you liek to setup VALIDATE PASSWORD plugin?
No
Please set the password for the root here
Set up your own password
Remove annonymous users?
Yes
Disallow root login remotely?
Yes (if you opt to develop only from your local server)
Remove test database and access to it?
No
Reload privilege tables now?
Yes

Use the command:

brew services start mysql

if you wish to run mysql server regardless of system reboots.

Using Your MySQL

If mysql server hasn't started,

mysql.server start
// if you wish to stop the server,
mysql.server stop
// if you wish to quit without stopping the server,
quit

Then login to the server.

mysql -u root -p

Connect your Django to MySQL

Make sure that django is installed in your virtual environment.

pip install mysqlclient

Databse and Table Creation

CREATE DATABASE database_name;
Or (CREATE DATABASE database_name character set utf8mb4 collate utf8mb4_general_ci;)
USE database_name;
CREATE TABLE table_name (name VARCHAR(20),field1 CHAR(1),field2 INT(10), dob DATE);
SHOW TABLES;

After the database and subsequent table are created, you can see the details of the table by usin the describe and explain command, which both work.

DESCRIBE table_name;

Inserting Values in a Table

INSERT INTO table_name VALUES('Williams','m','22','1998-03-15');

Viewing the Table

SELECT * FROM table_name;

Adding a Column to the Table

ALTER TABLE table_name ADD COLUMN new_field INT(10);
ALTER TABLE table_name ADD PRIMARY KEY(new_field)

Adding Values to the New Column

INSERT INTO table_name new_field VALUE ('001');

Selecting Particular Records

Using the SELECT WHERE command, we can select a specific record from the table as follows:

SELECT * FROM Information WHERE name = 'Williams';

Updating Selecting Records

To update information in a specific column for a specific record, the UPDATE command is used as follows:

UPDATE Information SET dob = '1999-02-02' WHERE name = Williams;

Django ORM Field <--> SQL Data Type

Display raw queries django is working on

Querysets have a query attribute containing the query to be executed:

print(MyModel.objects.filter(name="my name").query)

Obviously, this method only works when querysets call this .query method.

print(User.objects.create(name="jp").query)

won't work, as 'User' object has no attribute 'query'.

To delete an entire database and restart migration process

Delete all migration files in Django. Then delete the database.

DROP DATABASE name;

Lastly, create new database to migrate newly modified models.

0개의 댓글