首頁  >  文章  >  資料庫  >  Python全端介紹MySQL 資料庫

Python全端介紹MySQL 資料庫

coldplay.xixi
coldplay.xixi轉載
2020-12-17 10:38:482063瀏覽

mysql教學欄位Python全棧講解資料庫

Python全端介紹MySQL 資料庫

推薦(免費):mysql教學

主要三個面向:

##1.Linux終端指令

2.MySQL語句

3.Python呼叫

終端指令:

vi                                                      取得user表

sudo -i                             install python3-pip             安裝pip3

sudo pip3 install pymysql                 安裝服務端

sudo apt-get install mysql-client             安裝客戶端

sudo apt-get update                               讀取清單儲存為         對照下載清單並更新

sudo /etc /init.d/mysql status                  查詢狀態

sudo /etc/init.d/mysql stop         c 的             重啟服務

sudo /etc/init.d/mysql reload                 重新載入

mysql -h主機位址-u使用者名稱-p密碼   

#sudo -i                                          

#chmod  644 檔案名稱                                                                         3.進入設定文目錄

cp etc/msql.cnf/mysqld.cnf.bak                                                                    5.vi開啟中來源檔案中

[mysqld]  目錄##d

#character_set_server = utf8                                             

#資料備份:

參數:

          –all-databases                1.備份所有函式庫

          庫名                                2 .備份單一庫

          -B 庫1 庫2..                         多個庫

          庫名表1 表2…                               

mysql -uroot -p 21703e6553a3ac4c0d4f228fceee884e import pymysql

            >>>

python2模組安裝:

模組名稱:MySQLdb

#.sudo pipip install mysql-python

sqlalchemy 框架安裝:

    線上:sudo pip3 install sqlalchemy

##    離線:#oo

     SQLAlchemy-1.2.10.tar.gz

      $ cd SQLAlchemy-1.2.10

      $ sudo python3 setup.py python3

      >>> import sqlalchemy

      >>>

pymysql使用:##from pym##ffrom pym##ffrom pymfrom pym##ffrom pym##ff import *                                   導入模組

(db = my    1、建立資料庫連線

c = db.cursor())                                  與「標」為基礎c.execute(“insert ….”)                                                                        4、提交資料庫

c.close()                            5、關閉遊標物件 db.close()                                           

7.connect物件:

db = pymysql.connect(參數清單)

      1、host :主機位址,本機localhost

      2、port :連接埠號,預設3306

      3、user :使用者名稱

      4、password :密碼

 

##      6、charset :編碼方式,建議使用utf8

#8.連接物件的方法:

#資料庫連接物件( db)的方法

      1、db.close() 關閉連線

      2、db.commit() 提交至資料庫執行

      3、db.rollback() 回滾

      4、cur = db.cursor() 傳回遊標物件,用於執行特定SQL指令

9.遊標物件的方法:

遊標物件(cur)的方法

      1、cur.execute(sql指令,[清單]) 執行SQL指令

##      2、cur.close() 關閉遊標物件

      3、cur.fetchone() 取得查詢結果集的第一個資料

                  1 ) 取得n條

                        ((記錄1),(記錄2))

    #  5、cur.fetchall() 取得所有記錄

) :orm(Object Relation Mapping 物件關聯映射) 定義:將物件模型對應到MySQL資料庫中

SQL指令:

##/var/ lib/mysql                                              

#show variables like “autocommit”;                                    之後上問#                                                commit;                                                 提交事務(MySQL預設自動提交)

  • rollback;                                            終止事務

  • system sudo -i              對                        由資料直接進入終端機

  • show databases;                               與  已有庫

  • create database 函式庫名;                                 

    #create database 函式庫名charcater set utf8;                               指定字元集                                 檢視資料庫字元中加註
  • select database ();                                             
  • use 庫名;                                              切換庫

  • drop database 庫名;                           刪除庫

  • show tables;                                         查看已有表格

  • create table 表名(欄位名稱1 資料型,….);                           建立表

  • create
  • create#2#;##2#2#;查看表格字集

  • desc 表名;                                              檢視表結構

  • drop table                                  刪除表格

  • insert into 表名values(值1),(值2)…;                             插入完整記錄

    ##10110 ),…;               插入欄位資料
  • ##select * from 表名[where 條件];             查詢所有字段

  • select 字段名1,字段名稱2,…from 表名[where 條件];                查看欄位

  • ##alter table 表名add 欄位資料類型;        新增欄位

  • # alter table 表名add 欄位名稱資料型別first;                                字型內使用)

    #插入)
  • alter table 表名 名詞名稱;                                                                修改資料型別
  • ###################》 ##alter table 表名rename 表名;                                                 表重命名############delete from 表名where 條件;                                                 刪除表記錄(必須加where)########## ##update 表名set 欄位1=值1,欄位名稱2=值2,… where 條件       變更表記錄(必須加where)#############alter table 表名change 原名新名資料型別;                                             中命名上############ create table # 1 ##### create table 表名select * from 表名where false;                    複製表結構(不複製key)###
  • sex enum(「M」,」F」,」S」) not null defaulf 「S」                                                          詢問MySQL變數

  • select 欄位名稱清單from 資料表名稱清單;                                 中反含 含 name#.name), cname. t1 ,t2 where 條件                        多重表查詢

  • create index 登錄名on 表名()          新增普通索引

  • create table(… .index(欄位名稱),…)                                      建立資料表時建立一般索引                                    使用一般指標中刪除一般指標為

  • # show index from 表名;                                       姓名(欄位名稱);                       新增至所有指標中
  • create table 表名( ….​​ , unique key (字段名) );                             創建表時創建索引 |                        刪除唯一指標上
  • show unique index from 表格名稱;                                                          新增主鍵索引
  • #create table 表名( ….​​ , id int, primary key (字段名) );                創建表時創主鍵一索引
  • (id int primary uto_# ,)auto_increment=10000;    設定自成長起始值
  • alter table 名詞 modify id int auto_increment;           表名auto_increment=20000;                                                                            取下自成長上
  • #姓名   key;                                                                                                                                           key)
  • Non_Unique:1   :index                                                         普通索引(查詢結果)
  • Non_Unique:0   :unique                                   1# ##alter table 表名drop foreign key 外鍵名;                                   之後刪除作用時「「外鍵」##」

'

##show create table 表名;                                      

#建立外鍵:

create…t1 ();

create table t2(

foreign key(參考欄位名稱)

references 主表(被參考欄位名稱)

on delete 級聯動作

on update 級聯動作);

新增外鍵:

alter table 表名add

foreign key(參考欄位) references 主表(被參考欄位)

#on delete …

on update …

#級聯動作:

restrict(預設)不允許主表操作從表

cascade :跟隨刪除、更新

set null:主表變更後從表值為NULL

內連結:

select 欄位名稱from表1

inner join 表2 on 條件

inner join 表3 on條件…;

外連結.左連結:

以左表為主顯示查詢結果

         select 欄位名稱from 表1

         left join 表2 on 條件

         left join 表3 on 條件…;

右連結# 

## 結果

 

資料匯入:

load data  infile 「檔案名稱」

into table 表名

fields terminated by “分隔符號”

lines terminated by “n”;

資料導出:

select … from 表名

into outfile “/var/lib/mysql-files/檔名”

fields terminated by “分隔符號”

lines terminated by “n”;

資料恢復:

恢復單一函式庫

     mysql -uroot -p 70ac6e6bcad3db1ea90e039fa27df985 ~/xxx.sql

–all-databases  備份所有庫

庫名             備份單個庫

-B 庫1 庫2..     備份多個庫

庫名表1 表2…  備份指定庫指定表## #### 執行時間偵測:######   開啟:set profiling=1;######   關閉:set profiling=0;######   查詢執行記錄:show profilings;### ######SQL查詢:#########3.select … 聚合函數from 表名######1.where######2.group by…### ###4.having …######5.order by …######6.limit …;#########查詢巢狀:####### #select … from 表名where 條件(select ….);                         ######    2. #####       where#######       (country,gongji) in######       (select country,max(gongji) from sanguo group by count#where);表中實際存在的欄位######group by:給查詢結果分組######having:對查詢結果進一步篩選######distinct:不顯示欄位重複值#### ##show engines;                                           表名;                                                                     建立表格時指定儲存引擎# #####alter table 表名engine=innodb;                                   》

InnoDB特性(2檔):

      行級鎖定、支援外鍵、交易作業

      .frm(表結構,索引)、.ibd(表記錄)

MyISAM:

MyISAM特色(3文件):                             表級鎖定

      .frm(結構)、 .myd(記錄)、.myi(索引)

鎖定:

select :加讀鎖定之後別人不能更改表記錄,但可以進行查詢

insert、delete、update :加寫鎖定之後別人不能檢查、不能改

##鎖定粒度:

     表級鎖定:myisam

     行級鎖定:innodb

調優:

1.選擇適當的儲存引擎

2.常用欄位建立索引

3.where 避免使用!=、NULL判斷、or連結、

   like前置%、in、not in、*代替欄位、

資料類型:

資料型別:

int             大整數(4個位元組)  2**32 – 1(4294967295)

tinyintcob   #    295)

tinyint#    #    #「一個位元組)小尺寸#   有符號(signed預設):-128 ~ 127

                無符號(unsigned):0 ~ 255

smallint 整數(8位元組)

float           浮點數(4個位元組,7個有效位元)

       欄位名稱float(m,n) m:總位數n:小數位元數字

decimal         浮點數(28個有效位元)

      欄位名稱decimal(m,n)m:總位數n:小數位數

##  的倍數包裝成4個位元組

      餘數   位元組

        0      0

      1-2    0

      1-2    0

      1-2    0

 #        5 -6     3

       7-9     4

欄位名enum(值1,值2…);        #    鍵  單選(  名詞編號2…);                多重選擇(set)

    (以多項放在一個字串內用,編號隔開)

date:「YYYY-MM-DD」

############################################. #time:“HH:MM:SS”######datetime:“YYYY-MM-DD HH:MM:SS”######timestamp:“YYYY-MM-DD HH:MM:SS” ######datetime:不給值預設回傳Null######timestamp:不給值預設回傳系統時間######時間函數######now()                         返回伺服器目前的時間######curdate()                                                                             返回目前日期####o                    返回指定時間的年份######date(date)回傳指定時間的日期######time(date)                                     ### ##sum(欄位名稱):求和######max(欄位名稱):最大值######min(欄位名稱):最小值######count(欄位名稱):統計該欄位的個數######運算子: – * / %######時間運算子######select * from 表名######where 欄位名稱運算符(時間-interval 時間間隔單位);######時間間隔單位:1 day | 2hour | 1 minute | 2year | month######數值比較: =  !=  >  >= < <= < < ;=######字元比較: =  !=#####邏輯比較: and   or###

範圍內比較:

      1.where 字段名between 值1 and 價值2

      2.where 字段名in(值1,值2,….)

#      3.where 欄位名稱not in (值1,值2,…)

空白:where name is null

非空白:where name is not null

NILL:空值,只能用is或is not取符合

「」 : 空字串,用= 或  != 去配對

模糊比較:

     where字段名like 表達式

     表達式

        _ : 匹配單字

       %:符合0到多個字元

##        %:符合0到多個字元

##  

##排序:order by ASC | DESC

##顯示: limit 開始顯示位置,條數

     每頁顯示n筆記錄,顯示第m頁:

     limit(m-1)*n,n

MySQL 與Python 互動

# mysqlpython.py

# 导入mysql模块
from pymysql import *


class MysqlPython:
    def __init__(self, database,  # 库
                 host="127.0.0.1",  # ip地址
                 user="root",  # 用户名
                 password="123456",  # 密码
                 port=3306,  # 端口
                 charset="utf8"):  # 字符集
        self.host = host
        self.database = database
        self.user = user
        self.password = password
        self.port = port
        self.charset = charset

    def open(self):  # 创建数据库链接函数
        self.db = connect(host=self.host,
                          database=self.database,
                          user=self.user,
                          password=self.password,
                          port=self.port,
                          charset=self.charset)
        self.cur = self.db.cursor()  # 创建游标对象

    def close(self):  # 创建断开数据库链接 关闭游标函数
        self.cur.close()
        self.db.close()

    def zhixing(self, sql, L=[]):  # 创建pymysql.execute() 方法函数
        try:
            self.open()  # 链接数据库
            self.cur.execute(sql, L)  # 参数化执行SQL命令
            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()

資料庫使用者登入

from mysqlpython import Mysqlpython
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)
# (('7c4a8d09ca3762af61e59520943dc26494f8941b',),)

if len(result) == 0:
    print("用户名不存在")
elif result[0][0] == pwd2:
    print("登录成功")
else:
    print("密码错误")

ORM  sqlalchemy框架

# 创建一张表 # 连接数据库的模块 from 
sqlalchemy import create_engine fromsqlalchemy.ext.declarative
 import declarative_base from sqlalchemy import Column, Integer
,String engine = create_engine("mysql+pymysql://root:123456@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)

以上是Python全端介紹MySQL 資料庫的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:csdn.net。如有侵權,請聯絡admin@php.cn刪除