用MySQLdb包连接数据库

  1. 1. !/usr/bin/python
  2. 2. -- coding: utf-8 --

捣鼓捣鼓,跨过好多坑终于在Mac上配置好了开发环境,开始学Python啦!
今天学习的是Python连接数据库,安装了python-mysql包后,使用它自带的一些方法就可以连接了:
[python]

!/usr/bin/python

-- coding: utf-8 --

import sys
import MySQLdb

db = None

try:

# 连接数据库
db=MySQLdb.connect(host="localhost",
                 user="root",passwd="",
                 db="wegroup",
                 charset = "utf8",
                 unix_socket="/Applications/XAMPP/xamppfiles/var/mysql/mysql.sock")
                 # unix_socket 
cursor = db.cursor()

# 执行一个查询
cursor.execute("SELECT VERSION()")
data = cursor.fetchone()
# 显示数据库的版本
print "Database version: %s" % data

# 创建表user(id,name) 并插入数据
cursor.execute("CREATE TABLE IF NOT EXISTS user(id INT PRIMARY KEY AUTO_INCREMENT, name VARCHAR(30))")
cursor.execute("INSERT INTO user(name) VALUES('user1')")
cursor.execute("INSERT INTO user(name) VALUES('user2')")
# commit 后数据才会真正添加到数据表中!
db.commit()

# 更新数据
cursor.execute("UPDATE user SET name = %s WHERE id = %s",("xiaolai" , 2));

# 获取数据并遍历
cursor.execute("SELECT * FROM user");
# 获取描述信息
desc = cursor.description
print "描述信息:", desc
# 打印表头
print "%s %s" % (desc[0][0],desc[1][0])

# 获取结果数
count = cursor.rowcount
for i in range(count):
    row = cursor.fetchone()
    # 每一个都是一个元组
    print row[0], row[1]

finally:

# 记得要关闭!
if db:
    db.close()

[/python]