python入门篇5:数据库操作mysql/redis/mongodb/sqlite

1、mysql数据库操作

在python3中使用mysql数据库需要安装PyMysql模块。

pip3 install PyMysql

 【python访问mysql数据库的流程】

1.1、py与mysql交互的相关概念

【Connection对象】

Connection对象用于创建于数据库的连接,创建该对象时,需要调用connect()方法。connect()方法的参数说明

  • 参数host:连接mysql数据库的ip地址或主机名称;
  • 参数port:连接mysql数据库的端口号;
  • 参数database:连接的数据库名称;
  • 参数user:用户名称
  • 参数password:密码
  • 参数charset:通信采用的编码方式,推荐使用utf8,千万不要写成utf-8会报错。

Connetction对象的方法:

  • close()方法表示关闭
  • commit()方法:提交,用于增删改查操作
  • cursor()方法,返回一个Cursor游标对象,用于执行sql语句并获得结果

【Cursor对象】

cursor对象用于执行sql语句,一般是select、insert、update、delete操作。获取cursor对象需要调用Connection对象的cursor()方法。

cursor对象的方法:

  • execute(operation[,parameters]):执行语句,返回受影响的行数,主要执行增、删、改操作。
  • fetchone():执行查询语句,获取查询结果集的第一行数据,返回一个元组;
  • fetchall():执行查询语句,获取结果集的所有行,一行构成一个元组,再将这些元组装入一个元组返回。
  • close():关闭游标对象。

cursor对象的属性:

  • rowcount只读属性,表示最近一次execute()执行后受影响的行数。
  • connection获得当前连接对象。

1.2、操作示例

from pymysql import connect
class Pepole:
    def __init__(self):
        # 创建连接对象;注意charset='utf8' 不要写成utf-8,否则会报错
        self.conn = connect(host='10.9.7.1',port=3306,database='people',user='root',password='hnwz86505002',charset='utf8')
        # 获得游标对象Curosr
        self.cursor = self.conn.cursor()
    # 查询一条记录,返回是一个元组
    def find_one(self,sql):
        count = self.cursor.execute(sql)
        print("一共查询出%d条记录" % count)
        result = self.cursor.fetchone()
        return result
    # 查询所有记录,返回是一个元组
    def find_all(self,sql):
        count = self.cursor.execute(sql)
        result = self.cursor.fetchall()
        return result
    def find_param(self,sql,params):
        ''' 传递sql 参数的形式
        :param sql: sql语句
        :param params: 参数,是一个列表
        :return:
        '''
        self.cursor.execute(sql,params)
        return self.cursor.fetchall()

    def del_by_id(self,sql,id):
        # 如果执行成功,则返回1,否则是0
        result = self.cursor.execute(sql,id)
        self.conn.commit()
        return result

    def run(self):
        sql  ="select * from website;"
        # res = self.find_one(sql)
        # res = self.find_all(sql)
        sql2 = "select * from website where date=%s;"
        params = ['01']
        res = self.find_param(sql2,params)
        print(res)
        sql3 = "select * from website where id=%s;"
        id = ["11050512522720133128989"]
        del_result = self.del_by_id(sql3,id)
        print(del_result)
    def __del__(self):
        '''该对象销毁时,会自动关闭'''
        self.cursor.close()
        self.conn.close()

if __name__ == '__main__':
    pepole = Pepole()
    pepole.run()

2、redis数据库操作

python3使用redis需要安装redis模块,pip3 install redis

【StricRedis对象】

通过init创建对象,指定参数host、port、db。host默认是localhost,port默认是6379,db默认是0。

from redis import *
def main():
    try:
        redis_str= StrictRedis(host='192.168.2.10',port='6379',db='0')
        # set(key,value)方法设置值时,返回的结果是bool布尔类型True或False
        # set()方法操作时,如果这个key值已经存在,则为修改操作
        save_result = redis_str.set('city','beijing')
        print('类型:%s,返回值为%s'% (type(save_result),save_result))
        # get(key)方法返回值类型是bytes字节类型,当没有值时为None
        get_result = redis_str.get('city1')
        print('类型:%s,返回值为%s' % (type(get_result), get_result))
        # delete(key)方法,返回值类型为整型int,如果删除是没有这个key返回值为0,能正常删除返回值为1
        del_result = redis_str.delete('city2')
        print('类型:%s,返回值为%s' % (type(del_result), del_result))
        # keys返回值类型是list列表类型
        all_keys = redis_str.keys()
        print('类型:%s,返回值为%s' % (type(all_keys), all_keys))
    except Exception as e:
        print('连接出现异常',e)
    pass
if __name__ == '__main__':
    main()

3、mongodb数据库操作

4、sqlite数据库操作

import sqlite3
# 1.连接数据库
db_path = "./test.db"
# 如果数据库名称存在,读取数据库,如果数据库不存在,新建数据库
conn = sqlite3.connect(db_path)

# 2.获取游标
cur = conn.cursor()

# 3.获取数据库版本信息
cur.execute("select sqlite_version();")
print(cur.fetchone())

# 4.获取数据库中的表
table_info = cur.execute("select name from sqlite_master where type='table';").fetchall()
print(table_info)

# 5.建立表
cur.execute("drop table if exists book;")
cur.execute("create table book(id int, name text,price double);")
print(cur.execute("select name from sqlite_master where type='table';").fetchall())

# 6.向表中插入数据库
cur.execute("insert into book values(1,'python',50.2)")
cur.execute("insert into book values(2,'java',30.9)")
cur.execute("insert into book values(3,'go',20.40)")
cur.execute("insert into book values(4,'php',9.8)")
cur.execute("insert into book values(5,'c',60.7)")
cur.execute("insert into book values(6,'c++',56)")
cur.execute("insert into book values(7,'c#',48.56)")

# 7.批量插入数据
more_bookes = (
    (9,'北京',98.4),
    (10,'广州',88.32),
    (11,'郑州',75.44),
)
cur.executemany("insert into book values(?,?,?)",more_bookes)

# 8.提交操作
conn.commit()

# 9.查询数据
print(cur.execute("select * from book").fetchone())
rows =  cur.execute("select * from book").fetchall()
print(rows)

# 10.关闭连接
conn.close()



猜你喜欢

转载自blog.csdn.net/u013089490/article/details/88942262