python deal with mysql

来源:互联网 发布:开一家淘宝店 编辑:程序博客网 时间:2024/06/06 15:37

0. install

yum -y install python-devpip install MySQL-python

这个报名容易记错。是MySQL-python,注意大小写。

1.连接数据库

import MySQLdbdb = MySQLdb.connect  ("localhost","username","passwd","DBNAME",charset='utf8')

2.执行sql语句

“`
sqs = “select host from processlist”

cursor = db.cursor()
cursor.execute(sql)

results = cursor.fetchall()

for record in results:
col1 = record[0]
col2 = record[1]

3.close

db.close()

4.doc

文档很短。这是他蛋疼的地方,毕竟外部库。
http://mysql-python.sourceforge.net/MySQLdb.html
最后总结一下workflow

  1. db = MySQLdb.connect()
  2. cursor = db.cursor()
  3. sql = “”
  4. cursor.execute()
  5. results = cursor.fetchall()
  6. do with results
  7. db.close()
0 0