博主又在为将来的学习捣鼓各种环境,这次轮到了五花八门的数据库。这篇博客主要介绍这四个数据库和各自的可视化工具,并详细介绍如何用python连接数据库。说明一下,我这里连接的为局域网内另外一台电脑上安装的数据库,当然你也直接访问自己的本地数据库!
如对远程访问数据库有需要的小伙伴,可参考:Window下MySQL8.0.18的安装以及在局域网内实现数据库访问
本文目录
一、数据库简述
1.1 介绍:主要用途
-
SQL Server
SQL Server 是Microsoft公司推出的关系型数据库管理系统,它为关系型数据和结构化数据提供了更安全可靠的存储功能,可以构建和管理用于业务的高可用和高性能的数据应用程序。
-
MySQL
MySQL是一个关系型数据库管理系统,由瑞典MySQL AB 公司开发,属于 Oracle 旗下产品,体积小、速度快、总体拥有成本低,开放源码,一般中小型网站的开发都选择 MySQL 作为网站数据库。
-
MongoDB
MongoDB是一个基于分布式文件存储的数据库。由C++语言编写。旨在为WEB应用提供可扩展的高性能数据存储解决方案。
-
Redis
Redis(Remote Dictionary Server ),即远程字典服务,是一个开源的使用ANSI C语言语编写、支持网络、可基于内存亦可持久化的日志型、Key-Value数据库,并提供多种语言的API。
1.2 干货:默认端口号可视化工具
数据库 | 默认端口号 | 可视化工具 |
---|---|---|
SQL Server | 1433 | Navicat |
MySQL | 3306 | Navicat |
MongoDB | 27017 | Robo 3T |
Redis | 6379 | Redis Manager |
二、python连接数据库
(1) SQL Server数据库:pymssql
import pymssql
import pandas as pd
conn = pymssql.connect('127.0.0.1', 'sa', '你的sa密码', '你的数据库名')
# 这里(127.0.0.1)是本地IP地址
cursor = conn.cursor()
sql = "select * from " + '你的表名'
# 第1种方法
data1 = pd.read_sql(sql,con=conn)
# 第2种方法
cursor.execute(sql) # 执行sql语句
rows = cursor.fetchall() # 读取查询结果
data2 = pd.DataFrame(rows, columns=[x[0] for x in cursor.description])
cursor.close()
conn.close()
data1.head(1)
data2.head(1)
(2) MySQL数据库:pymysql
import pymysql
import pandas as pd
conn = pymysql.connect('192.168.3.6', 'root', '你的root密码', '你的数据库名')
# 这里(192.168.3.6)是访问数据库所在电脑的IP地址
cursor = conn.cursor()
sql = "select * from " + '你的表名'
# 第1种方法
data1 = pd.read_sql(sql,con=conn)
# 第2种方法
cursor.execute(sql) # 执行sql语句
rows = cursor.fetchall() # 读取查询结果
data2 = pd.DataFrame(rows, columns=[x[0] for x in cursor.description])
cursor.close()
conn.close()
data1.head(1)
data2.head(1)
(3) Redis数据库:redis
import redis
pool = redis.ConnectionPool(host='192.168.3.6', port=6379, db=0)
# 创建连接池,host为连接电脑IP地址,port为默认端口号3306,db选择连接的数据库
r = redis.Redis(connection_pool=pool) # 获取连接对象
r.set('name','value') # 插入数据
r.get('name') # 获得对应键的value值
(4) MongoDB数据库:pymongo
import pymongo
client = pymongo.MongoClient(host='192.168.3.6', port=27017)
# host为连接电脑IP地址,port为默认端口号27017
db = client.test # test为连接的数据库名
collection = db.students # students为选择的集合
student = {
'id': '20170101',
'name': 'Jordan',
'age': 20,
'gender': 'male'
}
result = collection.insert(student) # 向集合中插入值
print(result)