mindong 发表于 2018-8-3 11:27:14

python之MySQLdb库的使用

#创建数据库51ctotest  
>>> cur.execute('create database 51ctotest')
  
#选择数据库51ctotest
  
>>>con.select_db('51ctotest')
  
#创建表51cto,id自增
  
>>>cur.execute('create table if not exists 51cto(id int(11) PRIMARY KEY AUTO_INCREMENT,name varchar(20),age int(3))')
  
#插入一行数据,只给name、age赋值,让id自增
  
#使用sql语句,这里要接收的参数都用%s占位符.要注意的是,无论你要插入的数据是什#么类型,占位符永远都要用%s,后面的数值为元组或者列表
  
>>>cur.execute("insert into 51cto(name,age) values(%s,%s)",('fan',25))
  
#插入多行数据,用executemany,它会循环插入后面元组中的所有值
  
>>> cur.executemany("insert into 51cto(name,age) values(%s,%s)",(('te',25),('fei',26),('musha',25)))
  
3L
  
#查询
  
>>> cur.execute('select * from 51cto')
  
5L
  
#我们使用了fetchall这个方法.这样,cds里保存的将会是查询返回的全部结果.每条结果都是一个tuple类型的数据,这些tuple组成了一个tuple
  
>>> cur.fetchall()
  
((1L, 'fan', 25L), (2L, 'fan', 25L), (3L, 'te', 25L), (4L, 'fei', 26L), (5L, 'musha', 25L))
  
#再次查询,会看到查询不到结果,因为无论fetchone、fetchall、fetchmany指针是会发生移动的。所以,若不重置指针,那么使用fetchall的信息将只会包含指针后面的行内容。使用fetchall把指针挪到了最后,可以用scroll手动把指针挪到一个位置
  
>>> cur.fetchall()
  
()
  
>>> cur.scroll(1,'absolute')
  
>>> for i in cur.fetchall():
  
...   print i
  
...
  
(2L, 'fan', 25L)
  
(3L, 'te', 25L)
  
(4L, 'fei', 26L)
  
(5L, 'musha', 25L)
页: [1]
查看完整版本: python之MySQLdb库的使用