一、数据库
关系型的MySQL、SQL server、Oracle
非关系型的HBASE MySQL和python
MySQL和Python建立连接:pymysql库
第一步:安装pymysql模块
1.下载pymysql源码包
2.解压
3.配置环境变量
搜Python点击复制其文件位置 ,复制其路径
环境变量----path----新增----Ctrl+V----确定
4.cmd切换至pymysql源码包所在路径 cd 路径
5.运行setup.py文件 python setup.py install
第二步:检查pymysql模块
cmd中启动python cmd 进入
导入pymysql模块 没有报错则导入成功 import pymysql
如果pycharm中不能使用pymysql模块:
file---- setting---- Project:项目名---- Project Interpreter---- 点击加号添加pymysql包
另一种:
把PyMySQL-master 中 pymysql复制到Python文件中lib中
二、建立数据库连接
pymysql模块中的connect()方法可以建立与数据库的链接,并且返回连接对象
conn = pymysql.connect(参数列表)
host = 连接的MySQL主机名
port = 端口号
database = 数据库名称
user = 用户名
password = 密码
charset = utf8 注意:此处写成uft-8报错
例:
import pymysql
# 连接数据库
conn = pymysql.connect(
host = 'localhost',
port = 3306,
database = 'student',
user = 'root',
password = 'root',
charset = 'utf8'
)
# 创建游标
cursor = conn.cursor()
# 执行添加SQL语句
# 增
#s1 = "insert into user(uid,uname,upassword) values ('%d','%s','%s')" % (6,'wy','123456')
#cursor.execute(s1)
# 删
# s2 = "delete from user where uid=6"
# cursor.execute(s2)
# 改
s3 = "update user set uname='%s',upassword='%s' where uid=%d" % ('tt','123456',5)
cursor.execute(s3)
# 提交数据库执行
conn.commit()
# 执行全查语句
ss = "select * from user"
cursor.execute(ss)
# 获取查询结果的所有数据
data = cursor.fetchall()
print(data)
# 关闭游标
cursor.close()
# 关闭数据库连接
conn.close()
# 书写SQL语句 删除已存在的表
sql1 = "drop table if exists user"
# 执行SQL语句
cursor.execute(sql1)
# 书写SQL语句 新建表
# 定义多行需要用 三引号来注释
sql2 = '''create table user(
id int(10) primary key auto_increment,
name varchar(255) not null,
password varchar(255) not null) '''
# 执行SQL语句
cursor.execute(sql2)
# 添加 多个数据 [列表(元组)]
user_msg = [("admin", "123456"), ("lxy", "123"), ("zyh", "258369")]
cursor.executemany("insert into user(name,password) values (%s,%s)", user_msg)
# 单行数据
sql3 = "insert into user(name,password) values (%s,%s)" % ("wyy", "1108")
cursor.execute(sql3)