python mysqldb模块学习

 

使用示例库test 创建表user

 

CREATE TABLE `user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) CHARACTER SET latin1 NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=44 DEFAULT CHARSET=utf8
 

 

 

linux:#python

 

>>> import MySQLdb

>>> conn=MySQLdb.connect(user='root',passwd='password',host='127.0.0.1')  #mysql -h host  -u user -p password

>>> cur=conn.cursor()

>>> conn.select_db('test')  #选择使用的数据库

>>> cur.execute("insert into user values (7,'huming')") #insert操作

1L

>>> sqli="insert into user(id,name) value(%s,%s)" 

>>> cur.execute(sqli,(21,'s'))

1L

>>> sqlim="insert into user(id,name) values(%s,%s)"

>>> cur.executemany(sqlim,[(41,'41'),(42,'42'),(43,'43')]) #批量insert

3L

>>> cur.execute("delete from user where id>30")

3L

>>> cur.execute("update user set name='hu' where id=5") #update操作

1L

>>> conn.commit()  #表引擎为innodb时 需手动提交到数据库

>>> cur.executemany(sqlim,[(41,'41'),(42,'42'),(43,'43')])

3L

 

>>> conn.autocommit(1) #表引擎为innodb时 设置自动提交到数据库

 

>>> cur.execute("select * from user") #select 操作

14L

>>> cur.fetchone() #取一条

(1L, 'jakky')

>>> cur.fetchone() #取一条 游标已移

(2L, 'lucy')

>>> cur.fetchone()

(3L, 'mars')

>>> cur.fetchmany(5) #批量取五条

((4L, 'alex'), (5L, 'hu'), (7L, 'huming'), (12L, 'huming'), (13L, 'jkk'))

>>> cur.fetchmany(5)

((15L, 'jkk'), (19L, 'jkk'), (21L, 's'), (41L, '41'), (42L, '42'))

>>> cur.fetchmany(5)

((43L, '43'),)

>>> cur.fetchmany(5)

()

>>> cur.scroll(0,'absolute') #回正游标

>>> cur.fetchmany(5)

((1L, 'jakky'), (2L, 'lucy'), (3L, 'mars'), (4L, 'alex'), (5L, 'hu'))

 

>>> cur.fetchmany(cur.execute("select * from user")) #一次性取出所有

((1L, 'jakky'), (2L, 'lucy'), (3L, 'mars'), (4L, 'alex'), (5L, 'hu'), (7L, 'huming'), (12L, 'huming'), (13L, 'jkk'), (15L, 'jkk'), (19L, 'jkk'), (21L, 's'), (41L, '41'), (42L, '42'), (43L, '43'))

 

#关闭连接 防止内存泄露 退出

 

>>> cur.close() 

>>> conn.close()

>>> exit()

 

你可能感兴趣的:(mysqldb)