与python交互

pymysql

安装 :

  1. 在线 :sudo pip3 install pymysql
  2. 离线 :pymysql.tar.gz
    解压:setup.py
    python3 setup.py install

pymysql使用流程

  1. 建立数据库连接对象(db=pymysql.connect("root".
  2. 创建游标对象cur(操作数据库的对象)
  3. 游标对象:cur.execute("insert into sheng ...;")
  4. 提交到数据库执行 :db.commit()
  5. 关闭游标对象cur.close()
  6. 关闭数据库连接对象db.close()

示例 pymysql增删改

import pymysql

db = pymysql.connect(host="localhost",
             user="root",password="123456",
             database="db4",charset="utf8")
cursor = db.cursor()

try:
    # 1.在sheng表中插入1条记录
    sql_insert = 'insert into sheng(s_name) values("湖北省");'
    cursor.execute(sql_insert)
    # 2.在sheng表中删除id为8的记录
    sql_delete = 'delete from sheng where id=8;'
    cursor.execute(sql_delete)
    # 3.在sheng表中把id为1的记录的省名改为 浙江省
    sql_update = 'update sheng set s_name="浙江省" where id=1;'
    cursor.execute(sql_update)
    # 都执行成功再提交
    db.commit()
    print("ok")
except Exception as e:
    db.rollback()
    print("Failed",e)

cursor.close()
db.close()

示例2 SQL语句参数化

import pymysql

db = pymysql.connect(host="localhost",
             user="root",password="123456",
             database="db4",charset="utf8")
cursor = db.cursor()

try:
    s_name = input("请输入省份:")
    s_id = input("请输入该省编号:")
    sql_insert = 'insert into sheng(s_name,s_id) \
                  values(%s,%s);'
    L = [s_name,s_id]
    cursor.execute(sql_insert,L) #此处必须用列表传参
    db.commit()
    print("ok")
except Exception as e:
    db.rollback()
    print("Failed",e)

cursor.close()
db.close()
  1. db = pymysql.connect(参数列表)
    1. host :主机地址
    2. user :用户名
    3. password :密码
    4. database :库
    5. charset :编码方式,推荐utf8
    6. port :端口(3306)
  2. db (数据库连接对象) 的方法
    1. db.close() :断开连接
    2. db.commit() :提交到数据库执行
    3. db.cursor() :游标对象,用来执行SQL命令
    4. db.rollback() :回滚
  3. cursor 游标对象 的方法
    1. execute(SQL命令) :执行SQL命令
    2. close() :关闭游标对象
    3. fetchone() :获取查询结果的第1条数据
    4. fetchmany(n) :获取n条数据
    5. fetchall() :获取所有数据
      ## fetchmany(n) 和 fetchall() 得到的结果一定是一个大元组套着小元组 ((),(),())

WorkBench 图形化界面管理工具
Navicat : Windows中图形化界面管理工具

orm(Object Relation Mapping) 对象关系映射

  1. 示例
import sqlalchemy

class User:
    __tablename__ = "t1"
    id = Column(Integer,primary_key=True)
    name = Column(String(20))

解释:
一个类 User --> 数据库1张表
表中2个字段 :id 和 name

猜你喜欢

转载自www.cnblogs.com/ravener/p/9657375.html