Python操作MySQL实例讲解

一:如何使用

我们通常使用mysql-python,有以下步骤:

1.首先导入MySQLdb模块,import MySQLdb。

2.通过调用其中的connect连接,通常使用root登陆,密码我这里用的是默认密码,为空。

3.获得操作cursor。这相当于一个游标或指针,类似文件指针,总是指向数据库下一条或理解为你即将操作的位置。

4.进行相关操作。例如利用execute方法,传入相关sql语句,进行工作,如查询。

5.关掉游标和链接,防止下文对此进行非法操作。

二:简单实例
1.查询
#!/usr/bin/env python
#coding:utf-8

import MySQLdb

conn = MySQLdb.connect(host='127.0.0.1',user='root',passwd='',db='08day5') #参数分别为本机地址,用户,密码,数据库名
cur = conn.cursor()

ref_count = cur.execute('select * from new_db')
data = cur.fetchall()

cur.close()
conn.close()

print ref_count
print data

结果如下:

2.插入

#!/usr/bin/env python
#coding:utf-8

import MySQLdb

conn = MySQLdb.connect(host='127.0.0.1',user='root',passwd='',db='08day5')
cur = conn.cursor()

sql = "insert into new_db(id, name) values(%s,%s)"
params = (7, 'james')

cur.execute(sql, params)
conn.commit()

cur.execute('select * from new_db')
data = cur.fetchall()
print data

cur.close()
conn.close()

结果如下:

3.删除

#!/usr/bin/env python
#coding:utf-8

import MySQLdb

conn = MySQLdb.connect(host='127.0.0.1',user='root',passwd='',db='08day5')
cur = conn.cursor()

sql = "delete from new_db where id=%s"
params = (7,)

cur.execute(sql, params)
conn.commit()

cur.execute('select * from new_db')
data = cur.fetchall()
print data

cur.close()
conn.close()

结果如下:

4.修改

#!/usr/bin/env python
#coding:utf-8

import MySQLdb

conn = MySQLdb.connect(host='127.0.0.1',user='root',passwd='',db='08day5')
cur = conn.cursor()

sql = "update new_db set name=%s where id=%s"
params = ('kobe', 6)

cur.execute(sql, params)
conn.commit()

cur.execute('select * from new_db')
data = cur.fetchall()
print data

cur.close()
conn.close()

结果如下:

5.scroll(滚动)

scroll是对游标cursor的操作,类似于文件操作中文件指针的移动。

#!/usr/bin/env python
#coding:utf-8

import MySQLdb

conn = MySQLdb.connect(host='127.0.0.1',user='root',passwd='',db='08day5')
cur = conn.cursor(cursorclass = MySQLdb.cursors.DictCursor)   //假如此句将得到字典类型的数据,如图

cur.execute('select * from new_db')

data = cur.fetchone()
print data

#cur.scroll(-1, mode='relative')  #相对位置,相对当前位置的距离,cur一直指向下一个
cur.scroll(0, mode='absolute')  #绝对位置,不能为-1

data = cur.fetchone()
print data

cur.close()
conn.close(

如图:

三:简单查询用户历程

1.main.py

通过接收用户输入id和name,调用数据库对象的CheckValidate方法检测输入,并根据结果输出。

#!/usr/bin/env python
#coding:utf-8

from model.data_base import NewDb

def main():
    id = raw_input('id:')
    name = raw_input('name:')
    new_db = NewDb()          #实例化数据表对象
    result = new_db.CheckValidate(id, name)
    
    if not result:
        print 'no such person'
    else:
        print result

if __name__ == '__main__':
    main()

2.conf.py

这是用户登录mysql需要采用的配置文件。

#!/usr/bin/env python
#coding:utf-8

conn_dict = dict(host='127.0.0.1',user='root',passwd='',db='08day5')

3.data_base.py

这是数据库中一个数据表的类,提供对数据表操作的相应的方法。

Get_One() -> 得到一条数据,CheckValidate() ->检查符合条件的数据

#!usr/bin/env python
#coding:utf-8

from utili.sql_helper import MySqlHelper

class NewDb(object):
    def __init__(self):
        self.__helper = MySqlHelper()    #用helper类初始化一个成员
        
    def Get_One(self, id):
        sql = "select * from new_db where id=%s"
        params = (id,)
        return self.__helper.GetOne(sql, params)
 
    def CheckValidate(self, id, name):
        sql = 'select * from new_db where id=%s and name=%s'
        params = (id, name)
        return self.__helper.Get_One(sql, params)   #调用self.__helper的Get_One,而不是自己的

4.sql_helper.py

这是可以作为公共的数据库操作的类,data_base类可以说是对该类方法的一些封装。

#!/usr/bin/env python
#coding:utf-8

import MySQLdb
import conf

class MySqlHelper(object):
    def __init__(self):
        self.__conn_dict = conf.conn_dict    #利用配置文件初始化
    
    def Get_Dict(self, sql, params):         #以字典形式得到所有数据
        conn = MySQLdb.connect(**self.__conn_dict)      #接收字典参数需要用**
        cur = conn.cursor(cursorclass = MySQLdb.cursors.DictCursor)
        
        cur.execute(sql, params)
        data = cur.fetchall()
        
        cur.close()
        cur.close()
        return data

    def Get_One(self, sql, params):    #得到一条数据
        conn = MySQLdb.connect(**self.__conn_dict)
        cur = conn.cursor(cursorclass = MySQLdb.cursors.DictCursor)
        
        cur.execute(sql, params)
        data = cur.fetchone()
        
        cur.close()
        cur.close()
        return data

结果如下:

或:

以上就是相关实例,如果有新的我还会再追加。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值