python与mysql的链接

安装第三方链接mysqldb 的库
MySQLdb 是用于Python链接Mysql数据库的接口,它实现了 Python 数据库 API 规范 V2.0,基于 MySQL C API 上建立的。
centos 下
yum install -y MySQL-python
ubuntu
apt-get install -y python-mysqldb
 
或者
请访问 http://sourceforge.net/projects/mysql-python
(Linux平台可以访问:https://pypi.python.org/pypi/MySQL-python)从这里可选择适合您的平台的安装包,分为预编译的二进制文件和源代码安装包。
如果您选择二进制文件发行版本的话,安装过程基本安装提示即可完成。如果从源代码进行安装的话,则需要切换到MySQLdb发行版本的顶级目录,并键入下列命令:
 
gunzip MySQL-python-1.2.2.tar.gz
tar -xvf MySQL-python-1.2.2.tar
cd MySQL-python-1.2.2
python setup.py build
python setup.py install

 

 
 
windows环境python2.7安装MySQLdb
我电脑是64位,并且安装python不是默认路径,使用pip和mysql-python的exe文件安装都失败了。
确保安装了wheel
pip install wheel
 
 
去这个网站查找whl格式的MYSQL-python
http://www.lfd.uci.edu/~gohlke/pythonlibs/#mysql-python
下载对应版本我的是
MySQL_python-1.2.5-cp27-none-win_amd64.whl
在下载目录进入cmd(shift加右键),执行

pip install MySQL_python-1.2.5-cp27-none-win_amd64.whl
 
多python版本环境可以指定相关版本的python

python27 -m pip install MySQL_python-1.2.5-cp27-none-win_amd64.whl
 
测试一下
import MySQLdb
 
 
 
mysql链接配置
 
def connect_mysql():
    db_config = {
        'host': '192.168.48.128',
        'port': 3306,
        'user': 'xiang',
        'passwd': '123456',
        'db': 'python',
        'charset': 'utf8'
    }
    cnx = MySQLdb.connect(**db_config)
return cnx

 

查询mysql用户列表
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import MySQLdb
try:                   
    conn=MySQLdb.connect(host='localhost',user='root',passwd='toor',db='mysql',port=3306)     ##链接数据库
    cur=conn.cursor()                          ##使用cursor()方法获取操作游标
    cur.execute('select User,Host from user')  ##使用execute方法执行SQL语句
    qur_result  = cur.fetchall()               ##使用 fetchone() 方法获取一条数据库
 
    for record in qur_result:
        print record
    cur.close()     #关闭操作
    conn.close()    ##关闭链接
except MySQLdb.Error,e:
    print 'Myslq Rrror Msg:',e 

 

创建数据库,创建表,插入数据

#!/usr/bin/python
# -*- coding: UTF-8 -*-
import MySQLdb
try:                   
    db=MySQLdb.connect(host='localhost',user='root',passwd='toor',port=3306)     ##链接数据库
    cur=db.cursor()                          ##使用cursor()方法获取操作游标
    # 1 创建库
    cur.execute('create database if not exists test')  ##创建数据 test
    db.select_db('test')                       ##切换数据库
    # 2 创建表
    cur.execute('''
        create table stu_info(
            id int(5) not null primary key auto_increment,
            name char(10) not null,
            phone int(12) not null,
            class char(20)
            );
         ''')
    # 3 插入单条数据,.rollback()插入错误回滚
    try:
        info = ('abc',123456,'linux')
        sql = 'insert into stu_info values(null,%s,%s,%s)',info
        cur.execute(sql)  ##执行sql语句插入数据
        db.commit()                             ##提交,提交后无法回滚
    except:
        db.rollback()                           ##发生错误时回滚
    # 4 插入多条数据,.executemany()重复执行带参数的单条命令
    try:
        values_list = []
        for i in range(10):
            values_list.append(('abc_%s' i,'12345670%s' i,'python'))
        cur.executemany('insert into stu_info values(null.%s,%s,%s)',valuse_list)
        db.commit()
    except:
        db.rollback()   
    # 5  .fetchone() 查询返回一条结果
    cur.execute('select * from stu_info')       ##查询插入后的表
    qur_result  = cur.fetchone()                ##使用 fetchone() 方法获取一条数据库
    for record in qur_result:                   ##循环打印出获取到的每条数据
        print record     
    # 6  .fetchall() 返回全部结果
    cur.execute('select * from stu_info')       ##查询插入后的表
    qur_result  = cur.fetchall()                ##使用 fetchall() 全部的返回结果行
    print qur_result    
    # 7  .scroll() 移动指针到某一行,查询行后面的结果
    cur.execute('select * from stu_info')
    cur.scroll(14,'python')
    print cur.fetchall()
    
    cur.close()   ##关闭操作
    db.close()    ##关闭链接
except MySQLdb.Error,e:
    print 'Myslq Rrror Msg:',e 

 

commit() 提交
rollback() 回滚

cursor: 用来执行命令的方法

.callproc(self, procname, args):用来执行存储过程,接收的参数为存储过程名和参数列表,返回值为受影响的行数
.execute(self, query, args):执行单条sql语句,接收的参数为sql语句本身和使用的参数列表,返回值为受影响的行数
.executemany(self, query, args):执行单挑sql语句,但是重复执行参数列表里的参数,返回值为受影响的行数
.nextset(self):移动到下一个结果集

cursor用来接收返回值的方法:
.fetchall(self):接收全部的返回结果行.
.fetchmany(self, size=None):接收size条返回结果行.如果size的值大于返回的结果行的数量,则会返回cursor.arraysize条数据.
.fetchone(self):返回一条结果行.
.scroll(self, value, mode='relative'):移动指针到某一行.如果mode='relative',则表示从当前所在行移动value条,如果 mode='absolute',则表示从结果集的第一行移动value条.

 

 

posted on 2017-11-20 23:09  song-liang  阅读(231)  评论(0编辑  收藏  举报

导航