Python操作MySQL数据库

1. 安装mysql-python

运行下面的命令:

pip install mysql-python

安装以后:

import MySQLdb

如果没有出错,就表明安装成功。

2. 连接MySQL 

db = MySQLdb.connect("localhost", "root", "1", "fs")

其中localhost是服务器名,root是用户名,1是密码,fs是数据库名称,前提是MySQL数据库设置了相应的用户名和密码。

连接成功以后,通过

cur = db.cursor()

获取游标。

3. 查询数据

    cur.execute("select * from TableName where A = %s and B = %s order by C desc", (a, b))
    results = cur.fetchall()
    result = list(results)

cur.execute()执行查询语句,cur.fetchal()取得结果集,再用list()把结果集转换成tuple数组,剩下的就很容易处理了。

4. 写入数据

cur.execute("insert into A values(%s, %s, %s, %s)", (x1, x2, x3, x4))
db.commit()

不论写入的字段在表中是什么类型,都使用%s,否则会出错,写完以后需要commit()。

其他的还有Delete和Update操作,都是类似的,通过cur.execute()执行SQL语句,用%s代入参数就行了。

posted @ 2018-01-19 20:53  MSTK  阅读(444)  评论(0编辑  收藏  举报