csv怎么導(dǎo)入mysql數(shù)據(jù)庫(kù)

小億
82
2024-10-11 11:54:53
欄目: 云計(jì)算

要將CSV文件導(dǎo)入MySQL數(shù)據(jù)庫(kù),您可以按照以下步驟操作:

  1. 確保您已經(jīng)安裝了MySQL數(shù)據(jù)庫(kù)和Python環(huán)境。

  2. 打開(kāi)命令行或終端,輸入以下命令以安裝mysql-connector-python庫(kù)(如果尚未安裝):

pip install mysql-connector-python
  1. 創(chuàng)建一個(gè)CSV文件,例如data.csv,并確保其內(nèi)容格式正確。例如:
id,name,age
1,Alice,30
2,Bob,25
3,Charlie,22
  1. 編寫(xiě)Python腳本以將CSV數(shù)據(jù)導(dǎo)入MySQL數(shù)據(jù)庫(kù)。以下是一個(gè)示例腳本:
import csv
import mysql.connector
from mysql.connector import Error

# 連接到MySQL數(shù)據(jù)庫(kù)
try:
    connection = mysql.connector.connect(
        host='localhost',
        user='your_username',
        password='your_password',
        database='your_database'
    )

    if connection.is_connected():
        cursor = connection.cursor()

        # 刪除表(如果存在)
        cursor.execute("DROP TABLE IF EXISTS your_table")

        # 創(chuàng)建新表
        create_table_query = """CREATE TABLE your_table (
                                    id INT PRIMARY KEY,
                                    name VARCHAR(255),
                                    age INT
                                );"""
        cursor.execute(create_table_query)

        # 讀取CSV文件并插入數(shù)據(jù)
        with open('data.csv', mode='r') as csvfile:
            csv_reader = csv.DictReader(csvfile)
            insert_query = "INSERT INTO your_table (id, name, age) VALUES (%s, %s, %s)"
            cursor.executemany(insert_query, csv_reader)

        # 提交更改并關(guān)閉連接
        connection.commit()
        print("CSV data has been successfully imported to MySQL database.")

except Error as e:
    print(f"Error while connecting to MySQL: {e}")

finally:
    if connection.is_connected():
        cursor.close()
        connection.close()
        print("MySQL connection is closed")
  1. 在腳本中填寫(xiě)正確的數(shù)據(jù)庫(kù)連接信息(主機(jī)名、用戶名、密碼和數(shù)據(jù)庫(kù)名),并根據(jù)需要修改表名和字段名。

  2. 運(yùn)行Python腳本,CSV數(shù)據(jù)將被導(dǎo)入到MySQL數(shù)據(jù)庫(kù)中。

注意:根據(jù)您的需求和數(shù)據(jù)量,您可能需要調(diào)整腳本中的錯(cuò)誤處理、事務(wù)控制和性能優(yōu)化。

0