与Python交互

python3模块名:pymysql

conda install pymysql

conda install sqlalchemy

python2模块名:MySQLdb

import pymysql

# 1、创建与数据库连接对象
db = pymysql.connect(host='localhost', user='haoen110', password='123',
database='db4', charset='utf8')
# 2、利用db方法创建游标对象
cur = db.cursor() # 3、利用游标对象execute()方法执行SQL命令
cur.execute("insert into sheng values\
(16,300000,'台湾省');") # 4、提交到数据库执行
db.commit()
print("OK!") # 5、关闭游标对象
cur.close() # 6、断开数据库连接
db.close()
+----+--------+-----------+
| id | s_id | s_name |
+----+--------+-----------+
| 1 | 130000 | 河北省 |
| 2 | 140000 | 陕西省 |
| 3 | 150000 | 四川省 |
| 4 | 160000 | 广东省 |
| 5 | 170000 | 山东省 |
| 6 | 180000 | 湖北省 |
| 7 | 190000 | 河南省 |
| 8 | 200000 | 海南省 |
| 9 | 200001 | 云南省 |
| 10 | 200002 | 山西省 |
| 16 | 300000 | 台湾省 |
+----+--------+-----------+

pymysql 使用流程

1、建立数据库连接db = pymysql.connect(...)

2、创建游标对象cur = db.cursor()

3、游标方法cur.execute("insert ...")

4、提交到数据库db.commit()

5、关闭游标对象cur.close()

6、断开数据库连接db.close()

connect对象

  • 建立数据库连接db = pymysql.connect(...)

    • host:主机地址,本地 localhost
    • port:端口号,默认3306
    • user:用户名
    • password:密码
    • database:库
    • charset:编码方式,推荐使用utf8

数据库连接对象(db)的方法

  • db.close() 关闭连接
  • db.commit() 提交到数据库执行
  • db.rollback() 回滚
  • cur = db.cursor() 返回游标对象,用于执行SQL具体SQL命令

游标对象(cur)的方法

  • 创建游标对象cur = db.cursor()

    • cur.execute(SQL命令,[列表]) 执行SQL命令
    • cur.close() 关闭游标对象
    • cur.fetchone() 获取第一条数据
      • 是一个元组(1,100001,"河北省")
    • cur.fetchone() 获取第一条数据
    • cur.fetchmany(n) 获取n条数据
    • cur.fetchall() 获取所有记录
import pymysql

# 1、创建与数据库连接对象
db = pymysql.connect(host='localhost', user='haoen110', password='123',
database='db4', charset='utf8')
# 2、利用db方法创建游标对象
cur = db.cursor() # 3、利用游标对象execute()方法执行SQL命令
try:
sql_select = "select * from sheng"
cur.execute(sql_select) data1 = cur.fetchone()
print(data1)
print("*"*10) data2 = cur.fetchmany(3)
for m in data2:
print(m)
print("*"*10) data3 = cur.fetchall()
for m in data3:
print(m)
print("*"*10) except Exception as e:
db.rollback()
print("出现错误,已回滚", e) # 4、提交到数据库执行
db.commit()
print("OK!") # 5、关闭游标对象
cur.close() # 6、断开数据库连接
db.close()
(1, 130000, '河北省')
**********
(2, 140000, '陕西省')
(3, 150000, '四川省')
(4, 160000, '广东省')
**********
(5, 170000, '山东省')
(6, 180000, '湖北省')
(7, 190000, '河南省')
(8, 200000, '海南省')
(9, 200001, '云南省')
(10, 200002, '山西省')
(16, 300000, '台湾省')
**********
OK!

参数化

# 插入数据
import pymysql # 1、创建与数据库连接对象
db = pymysql.connect(host='localhost', user='haoen110', password='123',
database='db4', charset='utf8')
# 2、利用db方法创建游标对象
cur = db.cursor() # 3、利用游标对象execute()方法执行SQL命令 s_id = input("请输入省的编号:")
name = input("请输入省的名字:") try:
sql_insert = "insert into sheng(s_id,s_name) values(%s,%s);"
cur.execute(sql_insert, [s_id, name])
print("插入成功!") except Exception as e:
db.rollback()
print("出现错误,已回滚", e) # 4、提交到数据库执行
db.commit()
print("OK!") # 5、关闭游标对象
cur.close() # 6、断开数据库连接
db.close()
请输入省的编号:999
请输入省的名字:haha
插入成功!
OK! +----+--------+-----------+
| id | s_id | s_name |
+----+--------+-----------+
| 1 | 130000 | 河北省 |
| 2 | 140000 | 陕西省 |
| 3 | 150000 | 四川省 |
| 4 | 160000 | 广东省 |
| 5 | 170000 | 山东省 |
| 6 | 180000 | 湖北省 |
| 7 | 190000 | 河南省 |
| 8 | 200000 | 海南省 |
| 9 | 200001 | 云南省 |
| 10 | 200002 | 山西省 |
| 16 | 300000 | 台湾省 |
| 17 | 999 | haha |
+----+--------+-----------+

自己写封装

from pymysql import *

class Mysqlpython:
def __init__(self, database, host='localhost',
user='haoen110', password='123',
port=3306, charset='utf8'):
self.host = host
self.user = user
self.password = password
self.port = port
self.charset = charset
self.database = database def open(self):
self.db = connect(host=self.host,
user=self.user,
port=self.port,
database=self.database,
password=self.password,
charset=self.charset)
self.cur = self.db.cursor() def close(self):
self.cur.close()
self.db.close() def zhixing(self,sql,L=[]): # pymysql.execute(sql)
try:
self.open()
self.cur.execute(sql,L)
self.db.commit()
print("ok")
except Exception as e:
self.db.rollback()
print("Failed",e)
self.close() def all(self,sql,L=[]):
try:
self.open()
self.cur.execute(sql,L)
result = self.cur.fetchall()
return result
except Exception as e:
print("Failed",e)
self.close() # 创建数据库连接对象
# sqlh = Mysqlpython("db4")
# sql_insert = "insert into sheng(s_id,s_name) values(666,'jjj');"
# sqlh.zhixing(sql_insert) sql_select = "select * from sheng;"
data = sqlh.all(sql_select)
print(data)
ok
((1, 130000, '河北省'), (2, 140000, '陕西省'), (3, 150000, '四川省'), (4, 160000, '广东省'), (5, 170000, '山东省'), (6, 180000, '湖北省'), (7, 190000, '河南省'), (8, 200000, '海南省'), (9, 200001, '云南省'), (10, 200002, '山西省'), (16, 300000, '台湾省'), (17, 999, 'haha'), (18, 666, 'jjj'))

自制登录系统

create table user(
username varchar(20),
password char(40)
); insert into user values("SHE","7c4a8d09ca3762af61e59520943dc26494f8941b"); # sha1加密的123456
from hashlib import sha1

uname = input("请输入用户名:")
pwd = input("请输入密码:") # 用sha1给pwd加密
s1 = sha1() # 创建sha1加密对象
s1.update(pwd.encode("utf8")) # 指定编码
pwd2 = s1.hexdigest() # 返回16进制加密的结果 sqlh = Mysqlpython("db4")
select = "select password from user where username=%s;"
result = sqlh.all(select,[uname]) print(result) # 打印出来看看 if len(result) == 0:
print("用户名不存在")
elif result[0][0] == pwd2:
print("登录成功")
else:
print("密码错误")
请输入用户名:SHE
请输入密码:123456
(('7c4a8d09ca3762af61e59520943dc26494f8941b',),)
登录成功

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

  • 定义:

    • 把对象模型映射到MySQL数据库中
  • sqlalchemy模块安装

    • 示例:

        class User(Base):
      __tablename__="t1" # 声明要创建的表名
      id = Column(Integer, primary+key=True)
      name = Column(String(20))
      # 解释:User 一张表,id name
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column,Integer,String engine = create_engine("mysql+pymysql://haoen110:123@localhost/db4",encoding="utf8")
Base = declarative_base() # orm基类 class User(Base): # 继承Base基类
__tablename__ = "t123"
id = Column(Integer,primary_key=True)
name = Column(String(20))
address = Column(String(40)) Base.metadata.create_all(engine)
+---------+-------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+---------+-------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| name | varchar(20) | YES | | NULL | |
| address | varchar(40) | YES | | NULL | |
+---------+-------------+------+-----+---------+----------------+

MySQL和Python交互的更多相关文章

  1. mysql及python交互

    mysql在之前写过一次,那时是我刚刚进入博客,今天介绍一下mysql的python交互,当然前面会把mysql基本概述一下. 目录: 一.命令脚本(mysql) 1.基本命令 2.数据库操作命令 3 ...

  2. pymysql实现MySQL与Python交互

    常见MySQL操作 所需模块: pip3 install pymysql 查询(fetchone,fetchmany,fetchall): import pymysql #连接 con = pymys ...

  3. 数据库之MySQL与Python交互

    准备数据 创建数据表 -- 创建 "京东" 数据库 create database jing_dong charset=utf8; -- 使用 "京东" 数据库 ...

  4. MySql与python交互

    No1: 引入MySql:python2是Mysqldb,python3是pymysql No2: Connection对象 用于建立与数据库的连接 创建对象:调用connect()方法 conn=c ...

  5. Python全栈 MySQL 数据库(SQL命令大全、MySQL 、Python调用)

    为了梦想与了信仰    开局一张图   主要三个方面: 1.Linux终端命令 2.MySQL语句 3.Python调用   先删库 再跑路.....                         ...

  6. MysQL使用一与Python交互

    与python交互 在熟练使用sql语句的基础上,开始使用python语言提供的模块与mysql进行交互 这是我们在工作中大事要做的事 先学会sql是基础,一定要熟练编写sql语句 安装引入模块 安装 ...

  7. MySQL 存储引擎、锁、调优、失误与事务回滚、与python交互、orm

    1.存储引擎(处理表的处理器) 1.基本操作 1.查看所有存储引擎 mysql> show engines; 2.查看已有表的存储引擎 mysql> show create table 表 ...

  8. 开发使用mysql的一些必备知识点整理(四)与python交互

    与python交互 在熟练使用sql语句的基础上,开始使用python语言提供的模块与mysql进行交互 这是我们在工作中大事要做的事 先学会sql是基础,一定要熟练编写sql语句 安装引入模块 安装 ...

  9. MySQL——python交互

    与python交互之前我们需要安装一个MySQL的驱动模块Connector,这个驱动模块直接在cmd命令行输入 pip install mysql.connector 安装是否成功可以接着输入 py ...

随机推荐

  1. Python入门:全站url爬取

    <p>作为一个安全测试人员,面对一个大型网站的时候,手工测试很有可能测试不全,这时候就非常需要一个通用型的网站扫描器.当然能直接扫出漏洞的工具也有很多,但这样你只能算是一个工具使用者,对于 ...

  2. 洛谷 P2117 小Z的矩阵

    P2117 小Z的矩阵 题目描述 小Z最近迷上了矩阵,他定义了一个对于一种特殊矩阵的特征函数G.对于N*N的矩阵A,A的所有元素均为0或1,则G(A)等于所有A[i][j]*A[j][i]的和对2取余 ...

  3. GO语言为结构体排序

    package main import ( "fmt" "io/ioutil" "sort" "time" ) type ...

  4. iOS Core Animation具体解释(四)AutoLayout中的动画

    原创blog.转载请注明出处 blog.csdn.net/hello_hwc 欢迎关注我的iOS SDK具体解释专栏 http://blog.csdn.net/column/details/huang ...

  5. js插件---markdown如何使用

    js插件---markdown如何使用 一.总结 一句话总结:看文档,看api,看参数列表,看js调用插件的调用函数的参数(json) 1.js和css的问题:如何知道插件要引入哪些js和css? a ...

  6. 带你底层看Sqoop如何转换成MapReduce作业运行的(代码程序)

    补充 其实啊,我们知道,sqoop在运行的时候,最终会去转换成mapreduce作业,这个很简单,不多赘述.直接贴出来. 具体这些怎么运行的,见我如下这篇博客.这里只做一个引子. Sqoop Impo ...

  7. Boot_Strap基础

    1.数据行(.row)必须包含在容器(.container)中,以便为其赋予合适的对齐方式和内距(padding).如: <div class="container"> ...

  8. 00082_Set接口

    1.Set接口介绍 (1)Collection中可以存放重复元素,也可以不存放重复元素,那么我们知道List中是可以存放重复元素的.那么不重复元素给哪里存放呢?那就是Set接口,它里面的集合,所存储的 ...

  9. OpenStack_Swift源代码分析——ObjectReplicator源代码分析(1)

    1.ObjectorReplicator的启动 首先执行启动脚本 swift-init object-replicator start 此执行脚本的执行过程和ring执行脚本执行过程差点儿相同.找到s ...

  10. Cannot use isset() on the result of an expression (you can use "null !== expression" instead)

    if (isset($array[2])){ 抛出错误  Cannot use isset() on the result of an expression (you can use "nu ...