Python数据库连接笔记

2021-01-31  本文已影响0人  lk_erzanml
# -*- coding: utf-8 -*-
"""
Date : 
Author : Becld
Desc : 
"""
import pymongo
import pandas

def to_excels(filename):
    client = pymongo.MongoClient("127.0.0.1", 8102)

    db = client.admin  # 先连接系统默认数据库admin
    # 下面一条更改是关键,我竟然尝试成功了,不知道为啥,先记录下踩的坑吧
    db.authenticate("admin", "123456", mechanism='SCRAM-SHA-1')

    # 让admin数据库去认证密码登录,好吧,既然成功了,
    collections = client['jiangong_qa']  # 使用或者创建库
    tables = collections['jiangong_qa_v1']  # 使用或者创建表
    result=tables.find()
    pans=pandas.DataFrame(result)
    pans.to_excel(filename)


import pymongo

#1.创建客户端
#格式:client = pymongo.MongoClient(主机地址,端口号) 默认端口号为27017
client = pymongo.MongoClient('localhost')

#2.创建数据库
# 格式:client['数据库名']
db = client['test0502']

#3.创建表(如果这个表已经存在了)
#格式:数据库名['表名']
table = db['users']

#4.插入数据
# (1)插入单条数据
#格式:表名.insert(数据)
# table.insert({'name':'刘','age':19})
# table.insert({'name':'陈','age':29})

#(2)插入多条数据
# 格式:表名.insert_many(数据列表)
# user1= {'name':'莫','age':9}
# user2= {'name':'高','age':18}
# user3= {'name':'晓','age':40}
#
# table.insert_many([user1,user2,user3])

#5.查找
#(1)简单查找
#格式:表名.find(条件)
# users = table.find({'age':19})# select * from users where age=19
# for user in users:
#     print(user)

#(2)高级查找
'''
(>) 大于 - $gt     greater than
(<) 小于 - $lt        less than
(>=) 大于等于 - $gte
(<= ) 小于等于 - $lte
'''
# users = table.find({'age':{"$lte":19}})
# for user in users:
#     print(user)

#其它属性
#表里的总数据条数
print(table.count())

table.find_one()不带条件返回第一条数据
table.find_one({"name":"zhangsan"})带条件返回制定的数据

table.find()不带条件返回第一条数据
table.find({"name":"zhangsan"})带条件返回制定的数据
和find_one不同的是。find返回的是一个对象,可以迭代。

table.find().sort("key1") # 默认为升序
table.find().sort("key1", pymongo.ASCENDING) # 升序
table.find().sort("key1", pymongo.DESCENDING) # 降序

----------------------------
mongodb导出成表格命令:
Mongoexport –d 库名 –c 表名 –-type=csv –f 字段1,字段2,字段3  -o xiapi.csv





if __name__=="__main__":
    pass
    # client = pymongo.MongoClient("127.0.0.1",27017)
    # spiders_58=client['spiders_58']#使用或者创建库
    # area_url = spiders_58['area_url']#使用或者创建表
    # self.jiangong_qa_v1.update({"_id": line['_id']}, {"$set": {"fenci": text}})#更新数据库

    # client = pymongo.MongoClient("192.168.1.15", 27017)
    #
    # db = client.admin  # 先连接系统默认数据库admin
    # # 下面一条更改是关键,我竟然尝试成功了,不知道为啥,先记录下踩的坑吧
    # db.authenticate("admin", "123456", mechanism='SCRAM-SHA-1')
    #
    # # 让admin数据库去认证密码登录,好吧,既然成功了,
    # haha = client['haha']  # 使用或者创建库
    # ha = haha['ha']  # 使用或者创建表
    # ha.insert({"ha":"ha"})
    to_excels("nihao.xlsx")
# -*- coding: utf-8 -*-
"""
Date : 
Author : Becld
Desc : 
"""
import pymysql


# 连接数据库
# 使用pymysql对象中的connect方法   传递四个参数
# 第一个参数是   -h  localhost   主机
# 第二个参数是   -u  username    用户名
# 第三个参数是   -p  password    密码
# 第四个参数是   库名  database_name   库名
# database = pymysql.connect('localhost','root','123','first');
database = pymysql.connect('127.0.0.1', 'root', 'root', 'xinzeng')

cursor = database.cursor()#建立游标

sql="SELECT VERSION()"#查询数据库版本
sql="""CREATE TABLE runoob_tbl(
runoob_id INT NOT NULL AUTO_INCREMENT,
runoob_title VARCHAR(100) NOT NULL,
runoob_author VARCHAR(40) NOT NULL,
submission_date DATE,
PRIMARY KEY ( runoob_id )
)ENGINE=InnoDB DEFAULT CHARSET=utf8;"""#创建表
sql="""insert into runoob_tbl (runoob_title,runoob_author,submission_date)
    values ("xixi","hahah",NOW()),("nima","niba",NOW());
    """#插入数据
# 或者
sql="""insert into runoob_tbl (runoob_title,runoob_author,submission_date)
    values ("{}","{}",{});
    """.format("xixi","haha","NOW()")#插入数据
sql='select * from runoob_tbl;'#查询语句


# try:
#    # 执行sql语句
#    cursor.execute(sql)
#    # 提交到数据库执行
#    database.commit()
# except Exception as e:
#     print(e)
#    # Rollback in case there is any error
#     database.rollback()
#
# # 关闭数据库连接
# database.close()



# try:
#    # 执行SQL语句
#    cursor.execute(sql)
#    # 获取所有记录列表
#    results = cursor.fetchall()
#    for row in results:
#       print(row)
# except:
#    print("Error: unable to fecth data")
#
# # 关闭数据库连接
# database.close()



# try:
#    # 执行SQL语句
#    cursor.execute(sql)
#    # 获取所有记录列表
#    result=cursor.fetchone()#获取一条数据
#    print(result)
# except:
#    print("Error: unable to fecth data")
#
# # 关闭数据库连接
# database.close()

# 更新数据
sql="update runoob_tbl set runoob_title='{}' where runoob_id='{}'".format("Java",1)

try:
   # 执行SQL语句
   cursor.execute(sql)
   # 提交到数据库执行
   database.commit()
except:
   # 发生错误时回滚
   database.rollback()

# 关闭数据库连接
database.close()
# -*- coding: utf-8 -*-
"""
Date : 
Author : Becld
Desc : 
"""
import redis

pool = redis.ConnectionPool(host='192.168.1.15', port=63789, password="`123456`")
r = redis.Redis(connection_pool=pool)
r.set("hello","world")
h=r.get("hello")
h=h.decode("utf-8")
print(h)
上一篇下一篇

猜你喜欢

热点阅读