最近在学习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&