石家庄做网站的公司有哪些,网站推广套餐,网络安全工程师报名官网,手机推广赚钱平台最近在学习Python#xff0c;发现Python的众多类库给Python开发带来了极大的便利性。
由于项目中使用Mysql#xff0c;就考虑尝试使用Python调用Mysql#xff0c;方便写一些调试用的小程序代码。花了半天差了些资料#xff0c;自己动手#xff0c;做了个简单的demo#x…最近在学习Python发现Python的众多类库给Python开发带来了极大的便利性。
由于项目中使用Mysql就考虑尝试使用Python调用Mysql方便写一些调试用的小程序代码。花了半天差了些资料自己动手做了个简单的demo步骤如下
1到Python.org上查找所用的包我下载的是mysql.connector。
2代码编写import mysql.connector
主要分为5个步骤
a连接数据库 conn mysql.connector.connect(hostlocalhost, userroot,passwdpwd,dbtest)
b获取操作句柄cursor conn.cursor()
c执行sqlcursor.execute(sql)、cursor.executemany(sql, val)
d获取查询结果alldata cursor.fetchall()
(e)关闭连接cursor.close()、conn.close()
下面是测试用代码仅供参考
import os, sys, string
import mysql.connector
def main():
#connect to mysql
try:
conn mysql.connector.connect(hostlocalhost, userroot,passwdpwd,dbtest)
except Exception, e:
print e
sys.exit()
# get cursor
cursor conn.cursor()
# create table
sql create table if not exists product(Prd_name varchar(128) primary key, Count int(4))
cursor.execute(sql)
#insert one data
sqlinsert into product(Prd_name, Count) values(%s, %d) % (ATG, 200)
try:
cursor.execute(sql)
except Exception, e:
print e
#insert some datas
sql insert into product(Prd_name, Count) values(%s, %s)
val ((PPS, 400), (Jr,150), (Smt, 25))
try:
cursor.executemany(sql, val)
except Exception, e:
print e
#quary data
sql select * from product
cursor.execute(sql)
alldata cursor.fetchall()
#print data
if alldata:
for rec in alldata:
print rec[0],rec[1]
cursor.close()
conn.close()
if __name__ __main__:
main()
print(\nIts OK)