潭州课堂25班:Ph201805201 python 操作数据库 第五课 (课堂笔记)

一 用 python 操作 mysql 

1,导入 pymysql

2,检查配置文件,

3,端口转发

  如果 python 在本机,数据库在远程,或虚拟机则需要

4用 python 连接

# -*- coding: utf-8 -*-
# 斌彬电脑
# @Time : 2018/7/5

import pymysql
conn = pymysql.connect(
    host ='127.0.0.1',     # 远程 ip
    port = 3306,            #  mysql 端口
    user = 'binbin',        # 用户名
    password = 'qwe123',    # 密码
    db = 'data_1',          # 数据库
    charset = 'utf8'        #  编码
)
# print(conn)         #  是否连接成功

cur = conn.cursor()     # 定义游标

# ds = cur.execute( 'show databases' )    #  通过 cur.execute()  执行 sql 语句
# ds = cur.execute( 'select * from stu' )      #  查表
# print(ds)
# # one = cur.fetchone()                  #    找出第一条数据
# one = cur.fetchall()                    #    所有数据 以 元祖形式返回
# print(one)
# for i in one:
#     print(i)
#     print(*i)                           #  去()

table = '''create table t(
        id int, 
        name varchar(20) )
'''
# cur.execute(table)
cur.execute("insert t value(1,'bac') ")
conn.commit()                           #  提交事务

cur.close()                             #   关闭学游标
conn.close() # 关闭连接

cur.execute("select * from t") t = cur.fetchall() print(t) # 打印为 (),要加上 conn.commit() 提交事务事件

  

 二,用 pywhon 操作 redis

1 , pip install redis

2,查看配置文件,

# -*- coding: utf-8 -*-
# 斌彬电脑
# @Time : 2018/7/5 0005 11:24
import redis

# 建立连接
re = redis.Redis(
    host='127.0.0.1',
    port=6379
)

re.set('v1','k1')           #  单个
g1 = re.get('v1')           # 取出 v1 的值
print(g1)
# re.mset(a='a',b='b',c='c')  #  多个
# re.incr('key')              #  自增,key 的 value 是数字
# re.incr('key', 50)              #  自增50,key 的 value 是数字



re.方法

  

原文地址:https://www.cnblogs.com/gdwz922/p/9266324.html