Python调用Mysql

 最近在学习Python,发现Python的众多类库给Python开发带来了极大的便利性。

由于项目中使用Mysql,就考虑尝试使用Python调用Mysql,方便写一些调试用的小程序代码。花了半天差了些资料,自己动手,做了个简单的demo,步骤如下:

1)到Python.org上查找所用的包,我下载的是mysql.connector。

2)代码编写,import mysql.connector:

    主要分为5个步骤:

     (a)连接数据库: conn = mysql.connector.connect(host='localhost', user='root',passwd='pwd',db='test')

     (b)获取操作句柄:cursor = conn.cursor()

     (c)执行sql:cursor.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(host='localhost', user='root',passwd='pwd',db='test')

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

sql="insert 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("\nIt's OK")

 

你可能感兴趣的:(mysql,python)