首先是安装工具
Linux
Windows
创建数据库
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 "-" );
插入一条数据: insert into student (name,sex,age,tel) values(‘test‘,‘man‘,19,‘123456777‘)
MySQLdb的操作:
查询
1 #!/usr/bin/env python 2 #-*- encoding: utf-8 -*- 3 4 import MySQLdb 5 6 conn = MySQLdb.connect(host=‘127.0.0.1‘, user = ‘root‘,passwd =‘123456‘,db=‘yangshanlei‘) #连接mysql 7 cur = conn.cursor() #创建游标 8 9 reCount = cur.execute(‘select * from students‘) #查询sql语句 10 data = cur.fetchall() #把得到的数据都拿出来 11 12 13 cur.close() #关闭游标 14 conn.close() #关闭连接 15 16 print reCount #查询出影响行数 17 print data
insert
1 #!/usr/bin/env python 2 #-*- encoding: utf-8 -*- 3 4 import MySQLdb 5 6 conn = MySQLdb.connect(host=‘127.0.0.1‘, user = ‘root‘,passwd =‘123456‘,db=‘yangshanlei‘) #连接mysql 7 cur = conn.cursor() #创建游标 8 9 sql = "insert into students (name,sex,age,tel) values(%s,%s,%s,%s)" 10 params = (‘yang‘,‘man‘,19,‘2222222‘) 11 12 13 reCount = cur.execute(sql,params) 14 conn.commit() #insert update delete都需要加上commit 15 16 cur.close() #关闭游标 17 conn.close() #关闭连接 18 19 print reCount #查询出影响行数
1 #!/usr/bin/env python 2 #-*- encoding: utf-8 -*- 3 4 import MySQLdb 5 6 conn = MySQLdb.connect(host=‘127.0.0.1‘, user = ‘root‘,passwd =‘123456‘,db=‘yangshanlei‘) #连接mysql 7 cur = conn.cursor() #创建游标 8 9 li =[ 10 (‘www‘,‘usa‘,19,‘555‘), 11 (‘sss‘,‘usa‘,19,‘666‘) 12 ] 13 14 reCount = cur.executemany("insert into students (name,sex,age,tel) values(%s,%s,%s,%s)",li) 15 16 conn.commit() #insert update delete都需要加上commit 17 cur.close() #关闭游标 18 conn.close() #关闭连接 19 20 print reCount #查询出影响行数
delete
1 #!/usr/bin/env python 2 #-*- encoding: utf-8 -*- 3 4 import MySQLdb 5 6 conn = MySQLdb.connect(host=‘127.0.0.1‘, user = ‘root‘,passwd =‘123456‘,db=‘yangshanlei‘) #连接mysql 7 cur = conn.cursor() #创建游标 8 9 sql = "delete from students where name =%s" 10 params = (‘test1‘,) 11 12 13 reCount = cur.execute(sql,params) 14 conn.commit() #insert update delete都需要加上commit 15 16 cur.close() #关闭游标 17 conn.close() #关闭连接 18 19 print reCount #查询出影响行数
update
1 #!/usr/bin/env python 2 #-*- encoding: utf-8 -*- 3 4 import MySQLdb 5 6 conn = MySQLdb.connect(host=‘127.0.0.1‘, user = ‘root‘,passwd =‘123456‘,db=‘yangshanlei‘) #连接mysql 7 cur = conn.cursor() #创建游标 8 9 sql = "update students set name = %s where id = 1" 10 params = (‘sb‘,) 11 12 13 reCount = cur.execute(sql,params) 14 conn.commit() #insert update delete都需要加上commit 15 16 cur.close() #关闭游标 17 conn.close() #关闭连接 18 19 print reCount #查询出影响行数
原文:http://www.cnblogs.com/augustyang/p/6246926.html