gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-30 20:52:36 25 4
gpt4 key购买 nike

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

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 数据库的新手,所以我不熟悉命令/代码。所以我有几个问题:

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),端口号是您在创建服务器时定义的。服务器启动后,一个或多个客户端可以连接到数据库服务器。然后,您需要拥有一个拥有所有权限的 super 用户(如 root)和其他几个普通用户(可能权限较低)。
  1. What does mydb.cursor do?
  • :游标是一个可以执行SQL语句等操作的对象。您始终需要 Cursor 对象与 MySQL 服务器交互。如果您使用 native SQL 脚本与 MySQL 服务器交互,您实际上并不需要这个 cursor 对象,但是由于您使用 MySQLdb 作为 Python 包装器,因此您需要将它用作DB-API 要求您以这种方式与它们交互(游标对象是 Python DB-API 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 检索语句来检索它。创建数据库后,除非您想删除所有旧数据,否则很少需要重新创建。要使用它,您总是需要从数据库中读取。但是您可以将常用的 SQL(或调用一些存储的函数/过程)放入您的 Python 代码中,这样您就可以只调用一个函数以您想要的方式检索数据。

总的来说,我觉得你应该明白more about MySQL basics在急于使用它们之前。还有如何Install MySQL on Windows

关于python - 如何从 Python 中的 csv 文件创建 SQL 数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37516643/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com