2019-02-28
閱讀量:
1513
如何在python中使用多行sql語句
問題描述:
工作中經(jīng)常要用五六十行甚至更長(zhǎng)的SQL語句進(jìn)行查詢,大概就是這樣
select * from user
where uid < 10000
and age < 30;
現(xiàn)在要用查出來的數(shù)據(jù)在python中進(jìn)行數(shù)據(jù)分析,請(qǐng)問如何能把已經(jīng)寫好的多行SQL語句直接復(fù)制到python中執(zhí)行?
解決方法:
import MySQLdb
sql = "select * from user" +
"where uid < 10000" +
"and age < 30"
# 打開數(shù)據(jù)庫連接
db = MySQLdb.connect("localhost","testuser","test123","TESTDB" )
cursor = db.cursor()
# 使用execute方法執(zhí)行你的SQL語句
cursor.execute(sql)
# 使用 fetchone() 方法獲取一條數(shù)據(jù)
data = cursor.fetchone()
print "Database version : %s " % data
# 關(guān)閉數(shù)據(jù)庫連接
db.close()






評(píng)論(0)


暫無數(shù)據(jù)
CDA考試動(dòng)態(tài)
CDA報(bào)考指南
推薦帖子
0條評(píng)論
0條評(píng)論
0條評(píng)論
0條評(píng)論