標籤:python mysqldb
——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模組的安裝方法之一
[[email protected] ~]# 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 pythonimport 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 pythonimport 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.建立一個新文本,添加需要寫入資料庫的資訊 [每列用空格隔開]
[[email protected] ~]# cat info.txt 3 小陽 男4 小小 女5 小米 女6 小南 男
(2.批量插入
# -*- coding: utf-8 -*-#! /usr/bin/env pythonimport 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()
本文出自 “命運.” 部落格,請務必保留此出處http://hypocritical.blog.51cto.com/3388028/1695267
Python MySQLdb模組的安裝與使用