第十一章 连接数据库

一、数据库

关系型的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)

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

layroy

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值