使用mysql-connector
pip install 来安装
pip install mysql-connector
说明:mysqldb与mysql-connector的区别
MySQLdb is a C module that links against the MySQL protocol implementation in the libmysqlclient library. It is faster, but requires the library in order to work.
mysql-connector is a Python module that reimplements the MySQL protocol in Python. It is slower, but does not require the C library and so is more portable.
简单的来说就是mysqldb需要mysql中C的编译环境
下面以mysql-connector为例
import mysql.connector
if __name__ == '__main__':
db = mysql.connector.connect(user='root', password='数据库密码', database='数据库名称', charset='utf8')
try:
cursor = db.cursor() #定义一个数据库游标
sql = 'insert into question(title, content, user_id, created_date,comment_count) values("xxx", "xxx", 1, now(), 0)' #定义一个插入sql语句,语法同sql
cursor.execute(sql) #执行这个语句
qid = cursor.lastrowid #取最新列的id
print qid
sql = 'select * from question order by id desc limit 2' #查询语句
cursor.execute(sql)
for each in cursor.fetchall():
print each
db.commit() #提交事务
except Exception, e:
print e.message
db.rollback() #出现异常就数据回滚
db.close #关闭数据库