In this article, you will learn how to insert data into a MySQL table.
Inserting data into a MySQL table
Inserting data into a MySQL table is a fundamental operation in database management. Here are the steps involved in inserting data into a MySQL table:
Connect to the MySQL server
Before you can insert data into a MySQL table, you need to connect to the MySQL server. This is typically done using a MySQL client like MySQL Workbench or the command line interface. Here’s an example of how to connect using the command line interface:
mysql -u root -p
This command connects to the MySQL server as the root user and prompts you for a password. Once you’ve entered the password, you’ll be connected to the MySQL server.
Select the database you want to use
After you’ve connected to the MySQL server, you need to select the database you want to use. You can do this using the USE command. For example:
This command selects the database named my_database. All subsequent queries will be executed in the context of this database.
Create a SQL query to insert data into the table
To insert data into a MySQL table, you need to create a SQL query that specifies the table and the data you want to insert. Here’s an example query:
INSERT INTO my_table (column1, column2, column3) VALUES ('value1', 'value2', 'value3');
This query inserts a row into the my_table table with the values value1, value2, and value3 in the columns column1, column2, and column3, respectively. You can specify as many columns and values as you need.
Execute the query
After you’ve created the query, you need to execute it using the MySQL client. Here’s an example of how to execute the query using the command line interface:
mysql> INSERT INTO my_table (column1, column2, column3) VALUES ('value1', 'value2', 'value3');
Query OK, 1 row affected (0.00 sec)
This command executes the query and displays the number of rows affected by the query.
Verify the data was inserted correctly
After you’ve executed the query, you should verify that the data was inserted correctly. You can do this by running a SELECT query that retrieves the data you just inserted. For example:
SELECT * FROM my_table;
This query retrieves all the rows and columns from the my_table table. You should see the row you just inserted in the output.