MySQL和Python交互

與Python交互

python3模塊名:pymysqlpython

conda install pymysql
conda install sqlalchemymysql

python2模塊名:MySQLdbsql

import pymysql

# 一、建立與數據庫鏈接對象
db = pymysql.connect(host='localhost', user='haoen110', password='123', 
                     database='db4', charset='utf8')
# 二、利用db方法建立遊標對象
cur = db.cursor()

# 三、利用遊標對象execute()方法執行SQL命令
cur.execute("insert into sheng values\
            (16,300000,'臺灣省');")

# 四、提交到數據庫執行
db.commit()
print("OK!")

# 五、關閉遊標對象
cur.close()

# 六、斷開數據庫鏈接
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 使用流程

一、創建數據庫鏈接db = pymysql.connect(...)
二、建立遊標對象cur = db.cursor()
三、遊標方法cur.execute("insert ...")
四、提交到數據庫db.commit()
五、關閉遊標對象cur.close()
六、斷開數據庫鏈接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

# 一、建立與數據庫鏈接對象
db = pymysql.connect(host='localhost', user='haoen110', password='123', 
                     database='db4', charset='utf8')
# 二、利用db方法建立遊標對象
cur = db.cursor()

# 三、利用遊標對象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)
    
# 四、提交到數據庫執行
db.commit()
print("OK!")

# 五、關閉遊標對象
cur.close()

# 六、斷開數據庫鏈接
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

# 一、建立與數據庫鏈接對象
db = pymysql.connect(host='localhost', user='haoen110', password='123', 
                     database='db4', charset='utf8')
# 二、利用db方法建立遊標對象
cur = db.cursor()

# 三、利用遊標對象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)
    
# 四、提交到數據庫執行
db.commit()
print("OK!")

# 五、關閉遊標對象
cur.close()

# 六、斷開數據庫鏈接
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模塊安裝
    • 示例:app

      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    |                |
+---------+-------------+------+-----+---------+----------------+
相關文章
相關標籤/搜索