博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

Python Mysql 篇

Posted on 2016-03-22 11:09  善恶美丑  阅读(207)  评论(0编辑  收藏  举报

  

Python 操作 Mysql 模块的安装

linux:

    yum install MySQL-python
 
window:
    http://files.cnblogs.com/files/wupeiqi/py-mysql-win.zip
unbuntu
  https://pypi.python.org/pypi/MySQL-python/1.2.5#downloads
  解压后pip setup.py build 如果报错 EnvironmentError: mysql_config not found
  sudo apt-get install libmysqlclient-dev
  sudo updatedb
  locate mysql_config
  mysql_config的位置为:/usr/bin/mysql_config

  在mysql-python源码包下找到:setup_posix.py 文件,然后找到文件中的 mysql_config.path 将其值改为:/usr/bin/mysql_config,然后 sudo python    setup.py install ,就ok了
安装

SQL 基本使用:

1、数据库操作

show databases;
use [databasename];
create database  [name];

2、数据表操作

show tables;
 
create table students
    (
        id int  not null auto_increment primary key,
        name char(8) not null,
        sex char(4) not null,
        age tinyint unsigned not null,
        tel char(13) null default "-"
    );
desc chen.student; #desc获取表结构

3、数据操作

insert into student(name,sex,age,tel) values("chen","man","18","12311231123");

delete from student where id = 1;

update student set name = 'chen' where id =2;

select * from student;

Python MySQL API

import MySQLdb

# 连接到数据库
conn = MySQLdb.connect(host="127.0.0.1",user="root",passwd="chen27",db="chen")
cur = conn.cursor() #创建游标

#插入数据,注意mysql的占位符是%s(通过游标的方法execute插入数据)
recount = cur.execute('insert into student(name,sex,age,tel) values(%s,%s,%s,%s)',("chen27","man","19","11111"))

#提交事物
conn.commit()
# 关闭连接
cur.close #关闭游标
conn.close() # 关闭连接

print recount

批量插入数据

import MySQLdb

conn = MySQLdb.connect(host='127.0.0.1',user='root',passwd='chen',db='mydb')

cur = conn.cursor()

li =[
     ('alex','usa'),
     ('sb','usa'),
]
reCount = cur.executemany('insert into UserInfo(Name,Address) values(%s,%s)',li)

conn.commit()
cur.close()
conn.close()

print reCount

二、删除数据

import MySQLdb
 
conn = MySQLdb.connect(host='127.0.0.1',user='root',passwd='1234',db='mydb')
 
cur = conn.cursor()
 
reCount = cur.execute('delete from UserInfo')
 
#conn.rollback() 回滚操作
conn.commit() cur.close() conn.close()
print reCount

三、修改数据

import MySQLdb
 
conn = MySQLdb.connect(host='127.0.0.1',user='root',passwd='1234',db='mydb')
 
cur = conn.cursor()
 
reCount = cur.execute('update UserInfo set Name = %s',('alin',))
 
conn.commit()
cur.close()
conn.close()
 
print reCount

四、查数据

# ############################## fetchone/fetchmany(num)  ##############################
 
import MySQLdb
 
conn = MySQLdb.connect(host='127.0.0.1',user='root',passwd='1234',db='mydb')
cur = conn.cursor()
 
reCount = cur.execute('select * from UserInfo')
 
print cur.fetchone() # 取一条 fetchall()  取所有 fetchmany(num) 指定多少条
print cur.fetchone()
cur.scroll(-1,mode='relative')
print cur.fetchone()
print cur.fetchone()
cur.scroll(0,mode='absolute')
print cur.fetchone()
print cur.fetchone()
 
cur.close()
conn.close()
 
print reCount
 
 
 
# ############################## fetchall  ##############################
 
import MySQLdb
 
conn = MySQLdb.connect(host='127.0.0.1',user='root',passwd='1234',db='mydb')
#cur = conn.cursor(cursorclass = MySQLdb.cursors.DictCursor)
cur = conn.cursor()
 
reCount = cur.execute('select Name,Address from UserInfo')
 
nRet = cur.fetchall()
 
cur.close()
conn.close()
 
print reCount
print nRet
for i in nRet:
    print i[0],i[1]

一些参数

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条.