[파이썬] MySQL 데이터 추가와 삽입

MySQL is a popular relational database management system that is widely used for storing and managing data. In this blog post, we will explore how to add and insert data into a MySQL database using Python.

Establishing a Connection

Before we can add or insert data into a MySQL database, we need to establish a connection to the database using Python. We can use the mysql-connector-python library to achieve this. If you haven’t installed it yet, you can do so by running the following command:

pip install mysql-connector-python

Once the library is installed, we can begin by importing it in our Python script:

import mysql.connector

Next, we need to establish a connection to the MySQL database using the connect() function. We need to provide the necessary connection details such as the host, user, password, and database name:

mydb = mysql.connector.connect(
  host="localhost",
  user="yourusername",
  password="yourpassword",
  database="yourdatabase"
)

Adding Data

To add data to a MySQL database, we need to create a cursor object to execute SQL queries. We can do this by calling the cursor() method on the connection object:

mycursor = mydb.cursor()

Once we have the cursor object, we can execute SQL queries to add data to the database. The SQL syntax for adding data to a table is as follows:

INSERT INTO table_name (column1, column2, ...) VALUES (value1, value2, ...)

Let’s assume we have a table called “customers” with columns “name” and “email”. We can add a new customer by executing the following SQL query:

sql = "INSERT INTO customers (name, email) VALUES ('John', 'john@example.com')"
mycursor.execute(sql)

Don’t forget to commit the changes after adding data:

mydb.commit()

Inserting Data

In some cases, we may need to insert multiple rows of data at once. To achieve this, we can use the executemany() method instead of execute(). The executemany() method takes a SQL query template and a list of values to be inserted as parameters.

Let’s say we have a list of customers and their respective emails:

customers = [
  ('Alice', 'alice@example.com'),
  ('Bob', 'bob@example.com'),
  ('Charlie', 'charlie@example.com')
]

We can insert these customers into the “customers” table using the following code:

sql = "INSERT INTO customers (name, email) VALUES (%s, %s)"
mycursor.executemany(sql, customers)
mydb.commit()

Conclusion

In this blog post, we have learned how to add and insert data into a MySQL database using Python. By establishing a connection to the database, creating a cursor object, and executing SQL queries, we can easily add or insert data into the database. The mysql-connector-python library provides a convenient and simple way to work with MySQL databases in Python.

Remember to handle errors gracefully and close the database connection after you are done with your operations. Happy coding!