python连接MySQL数据库 - webdancer's Blog

python连接MySQL数据库

webdancer posted @ 2011年11月18日 19:37 in 编程语言 with tags python , 2450 阅读

python连接MySQL可以使用MySQLdb,数据库API规范可以参考PEP249,描述了类和应具有的属性和方法。MySQL的操作可以参考MySQL tutorial。

1.环境配置。

在Ubuntu11.10下面,自带python,但是没有MySQL,MySQLdb,所以首先安装MySQL,MySQLdb.

sudo apt-get install mysql-server
sudo apt-get install python-mysqldb

2.熟悉MySQL的基本操作。

连接Server:

mysql -h host -u user -p

输入Queries:

select version();

创建,使用database:

create database students;
use students;

查看数据库,表:

show databases;
show tables;

创建表:

create table webgrades(class varchar(10),number varchar(15), name varchar(20),grade int);

向表插入内容:

insert into webgrades values ('1','001','Justin',76);

从表查找内容:

select * from webgrades;

更多的内容参考MySQL tutorial。

3.python使用MySQLdb连接Server。

#! /usr/bin/env python
# -*- coding: utf8 -*-
import MySQLdb

#connect to the server
con=MySQLdb.connect(host='localhost',user='root',passwd='qweqwe',db='students')
#get cursor
cursor=con.cursor()
#execute the sql
operator="""insert into webgrades values (%s,%s,%s,%s)"""
para=[('1','200201000101','王丽',95),
      ('2','200201000201','赵宝刚',88),
      ('3','200201000301','杜玉',92)
      ]
cursor.executemany(operator,para)

#close the connection
con.close()

当然,更多的有关python连接数据库的知识参考python.org。


登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter
Host by is-Programmer.com | Power by Chito 1.3.3 beta | © 2007 LinuxGem | Design by Matthew "Agent Spork" McGee