我正在使用 python Django,我有一个 CSV 文件,其中包含 4 个字段名称、缩写、地址和学校类型。我有 3 个名为大学、大学类型和大学类型映射的数据库表。我有一个包含大学名称的 csv 列表,我想将其与数据库中存在的大学表进行比较,并想找出与该名称相对应的 id 和与大学类型相同的过程并找出其 ID。然后我想将这些值插入大学类型映射中。 我可以使用此方法从 CVS 读取数据,但仍停留在数据库搜索匹配上: 这是我用来阅读搜索的内容:
import csv
path = '/home/abi/Downloads'
file=open( path +"university.CSV", "r")
reader = csv.reader(file)
for line in reader:
t=line[1],line[2]
print(t)
姓名
NIT
Pune University
New University
Gujarat Technical University
Kuwait University - College of Business Administration جامعة الكويت - كلية العلوم الادارية
testuniversity
testuniversity
testuniversity23
testuniversity
Mumbai university
Mumbai university
California University
California University
California University
California University
California University
这是 csv 中的一个字段
我有一个包含字段“name”的大学 SQL 表,我想比较它的 CSV 名称并从中获取相应的 id
>>> import csv
>>> import pymysql
>>> import pymysql.cursors
>>> connection = pymysql.connect(user='root',password='root')
>>> path = '/home/abi/Downloads/'
>>> t=[]
>>> p=[]
>>> file = open(path +"university_list.csv - university_list.csv.csv","r" )
>>> reader = csv.reader(file)
>>> for line in reader:
... t=line[0]
... p=line[3]
... print t
最佳答案
也许你可以这样做:
import csv
import pymysql
path = '/home/abi/Downloads'
conn = pymysql.connect(host='127.0.0.1', port=3306, user='user',
passwd='pass', db='db_name', charset='utf8')
cursor1 = conn.cursor()
cursor2 = conn.cursor()
cursor3 = conn.cursor()
file=open( path +"university.CSV", "r")
reader = csv.reader(file)
for line in reader:
csv_school_name = line[0]
csv_school_type = line[3]
cursor1.execute("select id from schools_names where school_name = s%", csv_school_name)
corresponding_school_name_id = cursor1.fetchone()
cursor2.execute("select id from schools_types where school_type = s%", csv_school_type)
corresponding_school_type_id = cursor2.fetchone()
在此之后,您可以获得 school_name_id 和 school_type_id,然后您可以根据需要将这两个 id 插入表中。 我希望这可以帮助你。
你必须执行
cursor1.execute("select id from schools_names where school_name = s%", csv_school_name)
到时候,然后使用 fetchone(),如果你使用
school_id = cursor1.execute("select id from schools_names where school_name = s%", csv_school_name)
您将获得 table 的数量。
关于python - 加载 CSV 值,然后在 mysql 数据库中搜索匹配项,然后应用插入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44018091/