Table of contents:
mysql add, delete, modify
1. Connect to the database
To connect to a MySQL database, you need to first open the MySQL client in the terminal. Enter the following command:
mysql -u root -p
This will prompt you for your password. Enter your password and press Enter.
2. Create a database
To create a new database, use the following command:
CREATE DATABASE mydatabase;
To switch to a new database, use the following command:
USE mydatabase;
3. Create a table
To create a new table, use the following command:
CREATE TABLE mytable (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL,
email VARCHAR(50),
reg_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
);
This command will create a mytable
new table named with five columns: id, firstname, lastname, email, and reg_date.
- The id field is defined as INT type, UNSIGNED (not containing negative numbers), AUTO_INCREMENT (automatic increment), and as a primary key (PRIMARY KEY).
- firstname and lastname are defined as VARCHAR type, with a length of 30 characters, and are not allowed to be empty (NOT NULL).
- email is defined as VARCHAR type, has a length of 50 characters, and is allowed to be empty.
- reg_date is defined as TIMESTAMP type, DEFAULT is the current time (CURRENT_TIMESTAMP), and ON UPDATE is also the current time (CURRENT_TIMESTAMP).
4. Insert data
To insert data, use the following command:
INSERT INTO mytable (firstname, lastname, email)
VALUES ('John', 'Doe', '[email protected]');
This will mytable
insert a row into the table containing the values 'John', 'Doe' and '[email protected]'.
5. Query data
To query the data, use the following command:
SELECT * FROM mytable;
This returns mytable
all columns for all rows in the table. You can also use the WHERE clause in the query to filter the results, for example:
SELECT * FROM mytable WHERE id=1;
This will return id
rows with a value of 1.
6. Update data
To update the data, use the following command:
UPDATE mytable SET email='[email protected]' WHERE id=1;
This will update the column mytable
in the id
table row with a value of 1 email
to have a value of '[email protected]'.
7. Delete data
To delete data, use the following command:
DELETE FROM mytable WHERE id=1;
This will mytable
delete id
rows with value 1 from the table.
8. Close the connection
After completing the MySQL operation, to close the connection, use the following command:
QUIT;
This will exit the MySQL client and close the connection.