python 如何实现数据库的连接
记录一次phthon连接数据库的实例
一、源码
import pymysql
import re
def connectdb():
print('连接到mysql服务器...')
db = pymysql.connect(host="****", user="*******", password="******r", database="*****")
print('连接上了!')
return db
def closedb(db):
db.close()
def getNumber(db,table):
cursor = db.cursor()
sql = "SELECT count(*) FROM "+table
try:
cursor.execute(sql)
num1 = cursor.fetchall()
for row in num1:
print(table+"表数据量:",row[0])
except:
print("获取失败!")
return row[0]
def getfjdcar_idtofoundvin(db):
cursor = db.cursor()
sql = "SELECT jdcar_id FROM car_mt_wiper limit 0,10000 "
try:
cursor.execute(sql)
results = cursor.fetchall()
list=[]
for row in results:
jdcar_id = row[0]
list.append(foundvin(db,jdcar_id))
except:
print("数据获取失败!")
return list
def foundvin(db,str):
cursor = db.cursor()
sql = "SELECT vin FROM jd_car_vin where jdcar_id="+str
try:
cursor.execute(sql)
results = cursor.fetchall()
for row in results:
return row[0]
except:
print("vin获取失败!")
def main():
db = connectdb()
print(getNumber(db,"jd_car_vin"))
for i in getfjdcar_idtofoundvin(db):
print(i)
closedb(db)
if __name__ == '__main__':
main()
总结
拿来即用,拿走不谢!
|