Python操做MySQL数据库

1. 安装mysql-pythonpython

运行下面的命令:mysql

pip install mysql-python

安装之后:sql

import MySQLdb

若是没有出错,就代表安装成功。数据库

2. 链接MySQL 数组

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

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

链接成功之后,经过fetch

cur = db.cursor()

获取游标。spa

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数组,剩下的就很容易处理了。code

4. 写入数据

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

不论写入的字段在表中是什么类型,都使用%s,不然会出错,写完之后须要commit()。blog

其余的还有Delete和Update操做,都是相似的,经过cur.execute()执行SQL语句,用%s代入参数就好了。

相关文章
相关标签/搜索