Hướng dẫn how do i load csv file into mysql table using python? - làm cách nào để tải tệp csv vào bảng mysql bằng python?

Không chắc chắn những gì tôi đang thiếu ở đây nhưng mã này chạy mà không có bất kỳ thông báo lỗi nào, nhưng không có gì trong bảng. Tôi đang tải một giá trị CSV trong ba cột vào bảng MySQL

import csv
import MySQLdb

mydb = MySQLdb.connect[host='localhost',
    user='root',
    passwd='',
    db='mydb']
cursor = mydb.cursor[]

csv_data = csv.reader[file['students.csv']]
for row in csv_data:

    cursor.execute['INSERT INTO testcsv[names, \
          classes, mark ]' \
          'VALUES["%s", "%s", "%s"]', 
          row]
#close the connection to the database.
cursor.close[]
print "Done"

Sẽ đánh giá cao nếu người khác có thể có một cái nhìn.

CodeForester

36.2K16 Huy hiệu vàng104 Huy hiệu bạc128 Huy hiệu đồng16 gold badges104 silver badges128 bronze badges

Hỏi ngày 14 tháng 4 năm 2012 lúc 15:09Apr 14, 2012 at 15:09

Helen Neelyhelen NeelyHelen Neely

4.5618 Huy hiệu vàng39 Huy hiệu bạc61 Huy hiệu Đồng8 gold badges39 silver badges61 bronze badges

Tôi nghĩ rằng bạn phải làm mydb.commit[] tất cả các phần chèn vào.

Một cái gì đó như thế này

import csv
import MySQLdb

mydb = MySQLdb.connect[host='localhost',
    user='root',
    passwd='',
    db='mydb']
cursor = mydb.cursor[]

csv_data = csv.reader[file['students.csv']]
for row in csv_data:

    cursor.execute['INSERT INTO testcsv[names, \
          classes, mark ]' \
          'VALUES["%s", "%s", "%s"]', 
          row]
#close the connection to the database.
mydb.commit[]
cursor.close[]
print "Done"

Đã trả lời ngày 14 tháng 4 năm 2012 lúc 15:11Apr 14, 2012 at 15:11

Jakob Bowyerjakob BowyerJakob Bowyer

32,8K8 Huy hiệu vàng75 Huy hiệu bạc90 Huy hiệu Đồng8 gold badges75 silver badges90 bronze badges

5

Nếu bạn không có thư viện gấu trúc và sqlalchemy, hãy cài đặt chúng bằng PIPpandas and sqlalchemy libraries, install them using pip

pip install pandas
pip install sqlalchemy

Chúng ta có thể sử dụng gấu trúc và sqlalchemy để trực tiếp vào cơ sở dữ liệupandas and sqlalchemy to directly insert into the database

import csv
import pandas as pd
from sqlalchemy import create_engine, types

engine = create_engine['mysql://root:*Enter password here*@localhost/*Enter Databse name here*'] # enter your password and database names here

df = pd.read_csv["Excel_file_name.csv",sep=',',quotechar='\'',encoding='utf8'] # Replace Excel_file_name with your excel sheet name
df.to_sql['Table_name',con=engine,index=False,if_exists='append'] # Replace Table_name with your sql table name

Peter Szabo

1.0162 Huy hiệu vàng16 Huy hiệu bạc29 Huy hiệu đồng2 gold badges16 silver badges29 bronze badges

Đã trả lời ngày 23 tháng 9 năm 2019 lúc 4:10Sep 23, 2019 at 4:10

2

Câu trả lời trên có vẻ tốt. Nhưng một cách khác để làm điều này là thêm tùy chọn Auto Cam kết cùng với DB Connect. Điều này tự động cam kết mọi hoạt động khác được thực hiện trong DB, tránh sử dụng đề cập sql.commit[] mỗi lần.

 mydb = MySQLdb.connect[host='localhost',
        user='root',
        passwd='',
        db='mydb',autocommit=true]

một mã khác

4.75411 Huy hiệu vàng41 Huy hiệu bạc60 Huy hiệu Đồng11 gold badges41 silver badges60 bronze badges

Đã trả lời ngày 4 tháng 7 năm 2018 lúc 9:49Jul 4, 2018 at 9:49

Mahesh Kumaranmahesh KumaranMahesh Kumaran

8182 Huy hiệu vàng12 Huy hiệu bạc 30 Huy hiệu Đồng2 gold badges12 silver badges30 bronze badges

sử dụng pymsql nếu nó giúp

import pymysql
import csv
db = pymysql.connect["localhost","root","12345678","data" ]

cursor = db.cursor[]
csv_data = csv.reader[open['test.csv']]
next[csv_data]
for row in csv_data:
    cursor.execute['INSERT INTO PM[col1,col2] VALUES[%s, %s]',row]

db.commit[]
cursor.close[]

Đã trả lời ngày 14 tháng 5 năm 2020 lúc 7:24May 14, 2020 at 7:24

5

  from __future__ import print_function
import csv
import MySQLdb

print["Enter  File  To Be Export"]
conn = MySQLdb.connect[host="localhost", port=3306, user="root", passwd="", db="database"]
cursor = conn.cursor[]
#sql = 'CREATE DATABASE test1'
sql ='''DROP TABLE IF EXISTS `test1`; CREATE TABLE test1 [policyID int, statecode varchar[255], county varchar[255]]'''
cursor.execute[sql]

with open['C:/Users/Desktop/Code/python/sample.csv'] as csvfile:
    reader = csv.DictReader[csvfile, delimiter = ',']
    for row in reader:
        print[row['policyID'], row['statecode'], row['county']]
        # insert
        conn = MySQLdb.connect[host="localhost", port=3306, user="root", passwd="", db="database"]
        sql_statement = "INSERT INTO test1[policyID ,statecode,county] VALUES [%s,%s,%s]"
        cur = conn.cursor[]
        cur.executemany[sql_statement,[[row['policyID'], row['statecode'], row['county']]]]
        conn.escape_string[sql_statement]
        conn.commit[]

Jaffer Wilson

6.84710 Huy hiệu vàng55 Huy hiệu bạc130 Huy hiệu đồng10 gold badges55 silver badges130 bronze badges

Đã trả lời ngày 14 tháng 7 năm 2017 lúc 12:36Jul 14, 2017 at 12:36

Nếu đó là khung dữ liệu gấu trúc bạn có thể làm:

Gửi dữ liệu

csv_data.to_sql=[con=mydb, name='',
  if_exists='replace', flavor='mysql']

Để tránh việc sử dụng

import csv
import MySQLdb

mydb = MySQLdb.connect[host='localhost',
    user='root',
    passwd='',
    db='mydb']
cursor = mydb.cursor[]

csv_data = csv.reader[file['students.csv']]
for row in csv_data:

    cursor.execute['INSERT INTO testcsv[names, \
          classes, mark ]' \
          'VALUES["%s", "%s", "%s"]', 
          row]
#close the connection to the database.
mydb.commit[]
cursor.close[]
print "Done"
0.

Đã trả lời ngày 8 tháng 10 năm 2016 lúc 15:26Oct 8, 2016 at 15:26

2

Cách nhanh nhất là sử dụng trình tải khối MySQL bằng câu lệnh "Tải dữ liệu Infile". Đó là cách nhanh nhất cho đến nay hơn bất kỳ cách nào bạn có thể nghĩ ra trong Python. Nếu bạn phải sử dụng Python, bạn có thể gọi câu lệnh "Tải dữ liệu thông tin" từ chính Python.

Đã trả lời ngày 15 tháng 12 năm 2020 lúc 7:58Dec 15, 2020 at 7:58

JonasjonasJonas

Huy hiệu đồng 3911 bronze badge

Chúng ta có thể nhập CSV trong MySQL không?

Hãy nhập một số tệp CSV!Các tệp CSV có thể sử dụng dấu chấm phẩy thay vì dấu phẩy hoặc đặt các giá trị trong dấu ngoặc kép hoặc không.Như chúng ta đã thấy trong bài viết này, thật dễ dàng để nhập các tệp CSV vào cơ sở dữ liệu MySQL.Bạn có thể sử dụng dòng lệnh hoặc GUI.it's easy to import CSV files into a MySQL database. You can use either the command line or a GUI.

Cách nhanh nhất để nhập tệp CSV vào Workbench MySQL là gì?

Nhập tệp CSV bằng cách sử dụng MySQL Workbench Các bước sau đây là các bước bạn muốn nhập dữ liệu vào bảng: Mở bảng mà dữ liệu được tải.Xem lại dữ liệu, nhấp vào nút Áp dụng.MySQL Workbench sẽ hiển thị hộp thoại Áp dụng tập lệnh SQL vào cơ sở dữ liệu, nhấp vào nút Áp dụng để chèn dữ liệu vào bảng.Open table to which the data is loaded. Review the data, click Apply button. MySQL workbench will display a dialog “Apply SQL Script to Database”, click Apply button to insert data into the table.

Bài Viết Liên Quan

Chủ Đề