python连接数据库

1,环境准备

Python的MySQL数据库操作模块叫MySQLdb

自己百度安装方法(pip install MySQLdb

可以选择一种方法: from MySQLdb import connect
                                      from mysql.connector import connect

root@template liguang]# mysql -uroot -p123456 一台装有mysql的服务器


>>>
>>> import MySQLdb  #导入MySQLdb 模块(实际上用的是MySQLdb里面得connect模块)
>>>
>>> conn = MySQLdb.Connect(host='localhost',user='root',passwd='123456',db='test',charset='utf8')#与数据库建立连接
>>>
>>> cursor = conn.cursor()#创建一个游标对象
>>>
>>> sql = "create table user(id int,name varchar(30),password varchar(30))"#sql语句
>>>
>>> cursor.execute(sql)#执行sql语句
0L
>>> sql = "insert into user(id,name,password) values('1','xiaoming','111111')"
>>>
>>> cursor.execute(sql)#执行sql语句
1L
>>>
>>> conn.commit() # 提交事务,写入到数据库
>>>
>>> cursor.execute('show tables')#查看创建的表
2L
>>> cursor.fetchall()#返回上一个游标执行的所有结果,默认是以元组形式返回
((u'teacher',), (u'user',))
>>>
>>> cursor.execute('select * from user')#
1L
>>>
>>> cursor.fetchall() #返回上一个游标执行的所有结果,默认是以元组形式返回
((1L, u'xiaoming', u'111111'),)
>>>

-----------------插入多条数据:

>>> sql = 'insert into user(id,name,password) values(%s,%s,%s)'
>>>
>>>
>>> args = [('2','zhangsan','123456'),('3','liguang','123456')]
>>>
>>> cursor.executemany(sql,args)
2L
>>> conn.commit()
>>>
>>> sql = 'select * from user'
>>>
>>> cursor.execute(sql)
3L
>>>
>>> cursor.fetchall()
((1L, u'xiaoming', u'111111'), (2L, u'zhangsan', u'123456'), (3L, u'liguang', u'123456'))
>>>
>>>

-------------------------------------以字典形式返回结果:

默认显示的是元祖形式,要想返回字典形式,使得更易处理,就要用到cursor([cursorclass])中的cursorclass参数。

传入MySQLdb.cursors.DictCursor类:

如:

>>> cursor = conn.cursor(MySQLdb.cursors.DictCursor)
>>>
>>> sql = 'select * from user'
>>>
>>> cursor.execute(sql)
3L
>>>
>>> cursor.fetchall()
({'password': u'111111', 'id': 1L, 'name': u'xiaoming'}, {'password': u'123456', 'id': 2L, 'name': u'zhangsan'}, {'password': u'123456', 'id': 3L, 'name': u'liguang'})
>>>


遍历查询结果:


1 # /usr/bin/env python
  2 #-*- coding:utf-8 -*-
  3 import MySQLdb
  4 try:
  5     conn = MySQLdb.Connect(host='localhost',user='root',passwd='123456',connect_timeout=3,db='test',charset='utf8')
  6     cursor = conn.cursor()
  7     sql = "select * from user"
  8     cursor.execute(sql)
  9     for i in cursor.fetchall():
 10         print i
 11 except Exception,e:
 12         print ("Connection Error:"+str(e))
 13 finally:
 14     conn.close()

[root@template liguang]# python con_database.py
(1L, u'xiaoming', u'111111')
(2L, u'zhangsan', u'123456')
(3L, u'liguang', u'123456')








------------------------------------------------------------------------------------------------------------------------------------------------

python数据库游标对象详解:

python开发的MySQLdb遵从DB-API,实现了connect(),connect.cursor()等方法。。其他db类也实现了同样的方法,故可以很容易移植

DB-API规范的属性:

                      apilevel DB_API模块兼容的DB-API版本号

                       threadsafety 线程安全级别

                        paramstyle改模块支持的SQL语句参数风格

DB-API规范的方法:

                       connect()连接函数,生成一个connect对象,以提供数据库操作,同时函数参数也是固定好的

其中connect对象又有如下方法:

                         #所谓事务可以认为是一整套操作 只要有一处纰漏就废

                         close():关闭此connect对象,关闭后无法再进行操作,除非再次创建连接

                          commit():提交当前事务,如果是支持事务的数据库执行增删改查后没有commit则数据库默认回滚,白操作了

                          rollback():取消当前事务

                          cursor():创建游标对象

其中游标对象又有如下属性和方法:

                          常用方法:

                                                 close():关闭此游标对象

                                                 fetchone():得到结果集的下一行

                                                fetchmany([size = cursor.arraysize]):得到结果集的下几行
 

                                                fetchall():得到结果集中剩下的所有行
                                                   excute(sql[, args]):执行一个数据库查询或命令
                                                   excutemany(sql, args):执行多个数据库查询或命令
常用属性:
                              connection:创建此游标对象的数据库连接
 
                                     arraysize:使用fetchmany()方法一次取出多少条记录,默认为1
                                     lastrowid:相当于PHP的last_inset_id()

                             
  

                           


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值