我有一个tablename = myclass with field: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.
我有另一个数据库表“标记”,其中包含这些学生的标记:
student english physics
Jane 100 98
John 97 95
Maria 90 91
现在,我需要的程序是我需要搜索数据库的第一个名称“Jane”并且必须搜索关于Jane的文本文件。如果找到Jane则必须打印该行然后它必须连接秒标记数据库并打印Jane english 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
它会打印该行,但不知道如何连接marks.please help
**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.
请理解我的疑问并帮助我!
答案 0 :(得分:0)
一种方式:
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]