Python 专题一 python 使用 MySQL

来源:互联网 发布:macair怎么卸载软件 编辑:程序博客网 时间:2024/06/03 18:57

一.安装,如果测试python import MySQLdb不报错,说明安装成功

apt-get install python-setuptoolsapt-get install libmysqld-devapt-get install libmysqlclient-devapt-get install python-devpip install MySQL-python

二.安装配置mysql

修改配置

vi /etc/mysql/my.cnf

 查看编码

show variables like '%character%';

重新启动

/etc/init.d/mysql start

创建root密码

mysqladmin -u root password "newpass"

show databases      //显示数据库
create database student(数据库名)      //创建数据库student
use student      //进入student数据库

mysql> insert into mysql.user(Host,User,Password) values("localhost","testuser",password("testpass"));
这样就创建了一个名为:testuser 密码为:testpass 的用户。"localhost"改为"%",则可以任意电脑登录

mysql>flush privileges;//刷新系统权限表

创建表

create table students(name char(20) not null, age tinyint unsigned); 

查看表

describe students;

三.python 代码如下

#!/usr/bin/env pythonimport MySQLdbclass Database:    host    ="localhost"    user    ="testuser"    passwd  ="testpass"    db      ="test"    def __init__(self):        self.connection=MySQLdb.connect(host=self.host,                                        user=self.user,                                        passwd=self.passwd,                                        db=self.db                )    def query(self,q):        cursor=self.connection.cursor(MySQLdb.cursors.DictCursor)        cursor.execute(q)        return cursor.fetchall()    def __del__(self):        self.connection.close()if __name__ == "__main__":    db=Database()    q="DELETE FROM students"    db.query(q)    q="""    INSERT INTO students    VALUES    ('MIKE',39),    ('Michael',21),    ('Angela',21)    """    db.query(q)    q="""    SELECT * FROM students    WHERE age= 21    """    people=db.query(q)    for person in people:        print "Found: %s " % person['name']






原创粉丝点击