我有一个表名= myclass,字段为:student
**student**
1.Jane
2.John
3.Maria
我有一个文本文件“qwer.txt”,其中包含这些学生的详细信息,例如:
Jane is a good student and gets good marks.
john is a naughty one.
maria is a good student.
我有另一个数据库表“marks”,其中包含这些学生的分数:
student english physics
Jane 100 98
John 97 95
Maria 90 91
现在,我需要的程序是我需要搜索数据库的名字“Jane”,并且必须搜索有关 Jane 的文本文件。如果找到 Jane,则必须打印该行,然后它必须连接秒 Marks 数据库并打印简英文标记。
我做了一半的编码
import MySQLdb
db = MySQLdb.connect(host="localhost", # your host, usually localhost
user="root", # your username
passwd="mysql", # your password
db="sakila") # name of the data base
cursor = db.cursor()
# execute SQL select statement
cursor.execute("SELECT name FROM myclass")
# commit your changes
db.commit()
keywords=[]
#here fetchall() gets all the rows and we append carnames to key words
for i in cursor.fetchall():
keywords.append(i[0])
with open('qwer.txt','r') as file:
for line in file:
for key in keywords:
if key in line:
print line
它打印了该行,但缺少如何连接标记。请帮助
**MAIN OBJECTIVE**
It must search name one by one **from the table**(as input) and provide result to a text file.
It must connect another Marks database table and print marks to text file.
请理解我的疑问并帮助我!
最佳答案
一种方法:
import MySQLdb
db = MySQLdb.connect(host="localhost", # your host, usually localhost
user="root", # your username
passwd="mysql", # your password
db="sakila") # name of the data base
cursor = db.cursor()
# execute SQL select statement
cursor.execute("SELECT name,english,pysics FROM myclass c,marks m where c.student=m.student")
# commit your changes
rows=cursor.fetchall()
db.commit()
with open('qwer.txt','r') as file:
for line in file:
for row in rows:
if rows[0] in line:
print rows[0],'english mark',rows[1]
其他方式:
导入MySQLdb
db = MySQLdb.connect(host="localhost", # your host, usually localhost
user="root", # your username
passwd="mysql", # your password
db="sakila") # name of the data base
cursor = db.cursor()
# execute SQL select statement
cursor.execute("SELECT name FROM myclass")
# commit your changes
rows=cursor.fetchall()
)
with open('qwer.txt','r') as file:
for line in file:
for row in rows:
if rows[0] in line:
stmt="select english from marks where student = :student"
cursor.execute(stmt,dict(student=row[0]))
print "english marks:",cursor.fetchall()[0][0]
关于python - 通过检查数据库并放置来解析python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23955221/