python 操作mysql数据库

1 代码

#!/usr/bin/python
import mysql.connector
import sys, os

user = 'root'
pwd='root'
host='localhost'
db='amydb'

select_sql = 'select * from book'

cnx = mysql.connector.connect(user = user, password = pwd, host = host, database = db)
cursor = cnx.cursor()

try:
    cursor.execute(select_sql)
    for(name) in cursor:
        print(name)
except mysql.connector.Error as err:
    print("error:" + err.msg)
    sys.exit()
cnx.commit()
cursor.close()
cnx.close()

2 结果

('20140418101955036908', '数学', '张三', '0', datetime.datetime(1, 1, 1, 0, 0), 0, 0, datetime.datetime(2014, 4, 18, 10, 19, 56))
('20140418102116049939', '算法设计与分析', '未知', '0', datetime.datetime(1, 1, 1, 0, 0), 0, 0, datetime.datetime(2014, 4, 18, 10, 21, 30))

 3 环境

mysql 

python3.3

mysql.connector 地址:http://pan.baidu.com/s/1i31JiBz

posted on 2014-05-20 13:50  BestNow  阅读(213)  评论(0编辑  收藏  举报

导航