python2.7中MySQLdb的安装与使用详解

Python2.7中MySQLdb的使用

import MySQLdb
#1.建立连接
connect = MySQLdb.connect(
						'127.0.0.1', #数据库地址
						'root',      #数据库用户名
						'666666',	 #数据库密码
						'peewee',    #数据库名
						 3306,       #数据库端口(默认就是3306,端口不加引号,不然报错)   
						charset='utf8' #设置字符集编码
						)   
#2.实例化游标(是一个内存地址,存放的是python对mysql提交的命名和执行命令之后返回的结果)
cursor = connect.cursor()
#3.定义要执行sql语句(比如现在我们要创建一个teacher表)
sql = """create table if not exists teacher(
	id int primary key auto_increment,
	name char(20) not null,
	age char(3) not null,
	sex char(1) not null,
	email char(50) not null,
	address char(100) not null
	)"""
#4.提交命令
cursor.execute(sql) #通过execute()方法向mysql提交要执行的sql命令

#5.提交修改(将python提交给mysql的sql命令在mysql当中执行)
connect.commit()

#6.关闭游标(如果不关闭会占用内存资源)
cursor.close()

#7.关闭连接
connect.close()

#以上就是创建了一个teacher的表,去数据库上面查看,可以看得到
mysql> desc teacher;
+---------+-------------+------+-----+---------+----------------+
| Field   | Type        | Null | Key | Default | Extra          |
+---------+-------------+------+-----+---------+----------------+
| id      | int(11)     | NO   | PRI | NULL    | auto_increment |
| name    | varchar(50) | NO   |     | NULL    |                |
| age     | int(11)     | NO   |     | NULL    |                |
| sex     | varchar(50) | NO   |     | NULL    |                |
| email   | varchar(50) | NO   |     | NULL    |                |
| address | varchar(50) | NO   |     | NULL    |                |
+---------+-------------+------+-----+---------+----------------+

当然,如果你要想删除数据,改下sql语句就行

下面我们看看查看
connect = MySQLdb.connect(
						'127.0.0.1', #数据库地址
						'root',      #数据库用户名
						'666666',	 #数据库密码
						'peewee',    #数据库名
						 3306,       #数据库端口(默认就是3306,端口不加引号,不然报错)   
						charset='utf8' #设置字符集编码
						)   

cursor = connect.cursor()

sql = "select * from teacher where name = 'json' order by age desc"
cursor.execute(sql) #通过execute()方法向mysql提交要执行的sql命令

connect.commit()

results = cursor.fetchall() #fetchall()方法获取所有内容

for res in results:
name = res[1]
age = res[2]
sex = res[3]
email = res[4]
address = res[5]
print 'name:%s,age:%s,sex:%s,email:%s,address:%s'%(name,age,sex,email,address)

cursor.close()

connect.close()
可以看到结果
name:A,age:22,sex:男,email:123@qq.com,address:北京
name:B,age:20,sex:女,email:123@qq.com,address:天津南开

OK,MySQLdb就介绍到这里。欢迎吐槽~
posted @ 2017-11-07 14:16  于欢水  阅读(2905)  评论(0编辑  收藏  举报