——MySQLdb模块
常用的函数:
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):返回一条结果行
1.MySQLdb模块的安装方法之一[root@YunWei-129 ~]# easy_install mysql-python
2.MySQLdb模块实例用的表信息MariaDB [easy]> desc student;
+-------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+-------+
| id | int(11) | YES | | NULL | |
| name | varchar(20) | YES | | NULL | |
| sex | varchar(4) | YES | | NULL | |
+-------+-------------+------+-----+---------+-------+
3 rows in set (0.00 sec)
3.MySQLdb模块的连接与查询# -*- coding: utf-8 -*-
#! /usr/bin/env python
import MySQLdb
#连接数据库
connect = MySQLdb.connect(host="localhost",
user="root",
passwd="12345",
db="easy",
port=3306,
charset="utf8")
#创建游标
cursor = connect.cursor()
#执行SQL语句
SQL = cursor.execute("select * from student;")
#接收执行结果
EXE = cursor.fetchall()
#打印执行结果
for SQL in EXE:
print "ID : %-5s NAME : %-5s SEX : %-5s"% (SQL[0],SQL[1],SQL[2])
#关闭游标
cursor.close()
#关闭连接
connect.close()
4.MySQLdb模块的插入与更新# -*- coding: utf-8 -*-
#! /usr/bin/env python
import MySQLdb
#连接数据库
connect = MySQLdb.connect(host="localhost",
user="root",
passwd="12345",
db="easy",
port=3306,
charset="utf8")
#创建游标
cursor = connect.cursor()
#执行insert SQL语句
SQL_INSERT = cursor.execute("insert into student values(2,'小李','男');")
#执行update SQL语句
SQL_UPDATE = cursor.execute("update student set name='小洋',sex='女' where id=1;")
#执行select SQL语句
SQL_SELECT = cursor.execute("select * from student;")
EXE = cursor.fetchall()
#打印查看结果
for SQL in EXE:
print "ID : %-5s NAME : %-5s SEX : %-5s"% (SQL[0],SQL[1],SQL[2])
#提交
connect.commit()
#关闭游标
cursor.close()
#关闭连接
connect.close()
5.MySQLdb模块的批量插入 [有很多方法,方法之一]
(1.创建一个新文本,添加需要写入数据库的信息 [每列用空格隔开][root@YunWei-129 ~]# cat info.txt
3 小阳 男
4 小小 女
5 小米 女
6 小南 男
(2.批量插入# -*- coding: utf-8 -*-
#! /usr/bin/env python
import MySQLdb
#打开文本
touch = file('/root/info.txt')
#连接数据库
connect = MySQLdb.connect(host="localhost",
user="root",
passwd="12345",
db="easy",
port=3306,
charset="utf8")
#创建游标
cursor = connect.cursor()
#执行insert SQL语句
for info in touch.readlines():
ID,NAME,SEX = info.split()
cursor.execute("insert into student values(%d,'%s','%s');"% (int(ID),NAME,SEX))
#执行select SQL语句
SQL_SELECT = cursor.execute("select * from student;")
EXE = cursor.fetchall()
#打印查看结果
for SQL in EXE:
print "ID : %-5s NAME : %-5s SEX : %-5s"% (SQL[0],SQL[1],SQL[2])
#提交
connect.commit()
#关闭游标
cursor.close()
#关闭连接
connect.close()