如何从 Python 中的 csv 文件创建 SQL 数据库

how to create a SQL database from a csv file in Python

我需要从 csv 文件加载大型数据集(目前为 20gb,但将来会达到 100gb)。我在 python (PyCharm) 中使用 MySQLdb 模块。我还只需要 select 一些特定的列。到目前为止我试过这个:

import csv
import MySQLdb

mydb = MySQLdb.connect(host='localhost',
    user='root',
    passwd='',
    db='mydb')
cursor = mydb.cursor()

csv_data = csv.reader(file('collected_quotes_sample.csv'))
for row in csv_data:
    cursor.execute('INSERT INTO testcsv(RIC, Date, Time, Ask, Bid, BAS, window ) VALUES(%s, %s, %s, %s, %s, %s, %s)', row)
#close the connection to the database.
mydb.commit()
cursor.close()
print "Done"

但它提供了很多错误。我是 python 和 SQL 数据库的新手,所以我不熟悉 commands/codes。所以我有几个问题:

1. with MySQLdb.connect( host,user,passwd,db etc), what are host, user, password etc? to my understanding, they are credentials for my account in the computer. so do I need to put in my user account and password?
2. What does mydb.cursor do?
3. How to upload a csv file into a SQL database? and after the database is created, I can write a python script to work on it and there is no need to re read/create the database?

非常感谢!

回答您的问题

  1. with MySQLdb.connect( host,user,passwd,db etc), what are host, user, password etc? to my understanding, they are credentials for my account in the computer. so do I need to put in my user account and password?
  • 回答:host是服务器IP地址+端口号。 user/pwd是你在服务端创建的客户端用户。而一台主机内部可以创建多个DB,所以需要指定DB。通常你开始的时候,很可能使用的是localhost(127.0.0.1),端口号就是你在创建服务器时定义的。服务器启动后,一个或多个客户端可以连接到数据库服务器。然后,您需要拥有一个拥有所有权限的超级用户(如 root)和其他几个普通用户(可能权限较低)。
  1. What does mydb.cursor do?
  • 回答:游标是一个对象,可以执行SQL语句等操作。您始终需要 Cursor 对象与 MySQL 服务器交互。如果您使用本机 SQL 脚本与 MySQL 服务器交互,您实际上并不需要此 cursor 对象,但由于您使用 MySQLdb 作为 Python 包装器,那么您需要使用它,因为 DB-API 要求您以这种方式与它们交互(游标对象是 Python DB-[=48= 中指定的抽象] 2.0).
  1. How to upload a csv file into a SQL database? and after the database is created, I can write a python script to work on it and there is no need to re read/create the database?
  • 回答:一般情况下,您在问题中显示的代码正在执行上传过程。因此,一旦您成功上传,稍后您可以通过使用 MySQLdb 在 Python 中实施一些 SQL 检索语句来检索它。创建数据库后,除非您想删除所有旧数据,否则很少需要重新创建。要使用它,您总是需要从数据库中 read。但是您可以将常用的 SQL(或调用一些存储的 function/procedure)放入您的 Python 代码中,这样您就可以只调用一个函数以您想要的方式检索数据。

总的来说,我觉得你应该明白了more about MySQL basics before rushing to use them. And also how to Install MySQL on Windows

如果你想用 Python 创建一个 SQL 数据库只是为了玩两种语言,你应该尝试 SQLite:

import sqlite3
conn = sqlite3.connect("brand_new_db.db")

大功告成。

网上有很多教程。 This 例如,可能是一个很好的起点。