天天看點

python python操作MySQL

  MySQL是Web世界中使用最廣泛的資料庫伺服器,SQLite的特定是輕量級,可嵌入,但不能承受高并發通路,适合桌面和移動應用。而MySQL是為伺服器端設計的資料庫,能承受高并發通路,同時占用的記憶體也遠遠大于SQLite。此外,MySQL内部有多種資料庫引擎,最常用的引擎是支援資料庫事務的InnoDB。

一,安裝MySQL

這裡小編就不詳細介紹了,要是有不會安裝的可以參考下面部落格

 http://www.cnblogs.com/wj-1314/p/7573242.html

二,安裝MySQL-python

要想使python可以操作mysql 就需要MySQL-python驅動,它是python 操作mysql必不可少的子產品。

下載下傳位址:https://pypi.python.org/pypi/MySQL-python/

下載下傳MySQL-python-1.2.5.zip 檔案之後直接解壓。進入MySQL-python-1.2.5目錄:

>>python setup.py install

然後安裝pymysql

pip install pymysql
      

  

三,測試pymysql子產品

  測試非常簡單,檢查pymysql子產品是否可以正常導入。(在操作資料庫的時候,python2一般使用mysqldb,但是在python3中已經不再支援mysqldb了,我們可以用pymysql和mysql.connector。本文所有操作都是在python3的pymysql下完成的。)

python python操作MySQL

沒有報錯提示MySQLdb子產品找不到,說明安裝OK 

四,mysql 的基本操作

mysql> show databases;  // 檢視目前所有的資料庫
+--------------------+
| Database           |
+--------------------+
| information_schema |
| csvt               |
| csvt04             |
| mysql              |
| performance_schema |
| test               |
+--------------------+
rows in set (0.18 sec)

mysql> use test;   //作用與test資料庫
Database changed
mysql> show tables;   //檢視test庫下面的表
Empty set (0.00 sec)

//建立user表,name 和password 兩個字段
mysql> CREATE  TABLE  user (name VARCHAR(20),password VARCHAR(20));  Query OK, 0 rows affected (0.27 sec)

//向user表内插入若幹條資料
mysql> insert into user values('Tom','1321');
Query OK, 1 row affected (0.05 sec)

mysql> insert into user values('Alen','7875');
Query OK, 1 row affected (0.08 sec)

mysql> insert into user values('Jack','7455');
Query OK, 1 row affected (0.04 sec)

//檢視user表的資料
mysql> select * from user;
+------+----------+
| name | password |
+------+----------+
| Tom  | 1321     |
| Alen | 7875     |
| Jack | 7455     |
+------+----------+
rows in set (0.01 sec)

//删除name 等于Jack的資料
mysql> delete from user where name = 'Jack';
Query OK, 1 rows affected (0.06 sec)

//修改name等于Alen 的password 為 1111
mysql> update user set password='1111' where name = 'Alen';
Query OK, 1 row affected (0.05 sec)
Rows matched: 1  Changed: 1  Warnings: 0

//檢視表内容
mysql> select * from user;
+--------+----------+
| name   | password |
+--------+----------+
| Tom    | 1321     |
| Alen   | 1111     |
+--------+----------+
rows in set (0.00 sec)
      

五,python 操作mysql資料庫基礎

  這裡盜圖一張,以流程圖的方式展示python操作MySQL資料庫的流程:

python python操作MySQL

1,執行SQL,具體語句如下:

#coding=utf-8
import MySQLdb

# 打開資料庫連接配接      
conn= MySQLdb.connect(
        host='localhost',
        port = 3306,
        user='root',
        passwd='123456',
        db ='test',
        )

# 使用cursor()方法擷取操作遊标 
cur = conn.cursor()

#建立資料表
#cur.execute("create table student(id int ,name varchar(20),class varchar(30),age varchar(10))")

#插入一條資料
#cur.execute("insert into student values('2','Tom','3 year 2 class','9')")


#修改查詢條件的資料
#cur.execute("update student set class='3 year 1 class' where name = 'Tom'")

#删除查詢條件的資料
#cur.execute("delete from student where age='9'")

# 關閉遊标
cur.close()

# 送出,不然無法儲存建立或者修改的資料
conn.commit()

# 關閉資料庫連接配接
conn.close()
      

2,擷取新建立資料自增ID  

import pymysql
  
conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='123', db='t1')
cursor = conn.cursor()
cursor.executemany("insert into hosts(host,color_id)values(%s,%s)", [("1.1.1.11",1),("1.1.1.11",2)])
conn.commit()
cursor.close()
conn.close()
  
# 擷取最新自增ID
new_id = cursor.lastrowid
      

3、擷取查詢資料

import pymysql
  
conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='123', db='t1')
cursor = conn.cursor()
cursor.execute("select * from hosts")
  
# 擷取第一行資料
row_1 = cursor.fetchone()
  
# 擷取前n行資料
# row_2 = cursor.fetchmany(3)
# 擷取所有資料
# row_3 = cursor.fetchall()
  
conn.commit()
cursor.close()
conn.close()
      

          fetchone()方法可以幫助我們獲得表中的資料,可是每次執行cur.fetchone() 獲得的資料都不一樣,換句話說我沒執行一次,遊标會從表中的第一條資料移動到下一條資料的位置,是以,我再次執行的時候得到的是第二條資料。fetchone()函數的傳回值是單個的元組,也就是一行記錄,如果沒有,就傳回null

  fetchall() 函數的傳回值是多個元組,即傳回多個行記錄,如果沒有,傳回的是()、

注:在fetch資料時按照順序進行,可以使用cursor.scroll(num,mode)來移動遊标位置,如:

  • cursor.scroll(1,mode='relative')  # 相對目前位置移動
  • cursor.scroll(2,mode='absolute') # 相對絕對位置移動

4、fetch資料類型

  關于預設擷取的資料是元祖類型,如果想要或者字典類型的資料,即:

import pymysql
  
conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='123', db='t1')
  
# 遊标設定為字典類型
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
r = cursor.execute("call p1()")
  
result = cursor.fetchone()
  
conn.commit()
cursor.close()
conn.close()
      

5,插入資料

通過上面execute()方法中寫入純的sql語句來插入資料并不友善。如:

>>>cur.execute("insert into student values('2','Tom','3 year 2 class','9')")

我要想插入新的資料,必須要對這條語句中的值做修改。我們可以做如下修改:

#coding=utf-8
import MySQLdb

conn= MySQLdb.connect(
        host='localhost',
        port = 3306,
        user='root',
        passwd='123456',
        db ='test',
        )
cur = conn.cursor()

#插入一條資料
sqli="insert into student values(%s,%s,%s,%s)"
cur.execute(sqli,('3','Huhu','2 year 1 class','7'))

cur.close()
conn.commit()
conn.close()
      

     假如要一次向資料表中插入多條值呢?

    executemany()方法可以一次插入多條值,執行單挑sql語句,但是重複執行參數清單裡的參數,傳回值為受影響的行數。

#coding=utf-8
import MySQLdb

conn= MySQLdb.connect(
        host='localhost',
        port = 3306,
        user='root',
        passwd='123456',
        db ='test',
        )
cur = conn.cursor()

#一次插入多條記錄
sqli="insert into student values(%s,%s,%s,%s)"
cur.executemany(sqli,[
    ('3','Tom','1 year 1 class','6'),
    ('3','Jack','2 year 1 class','7'),
    ('3','Yaheng','2 year 2 class','7'),
    ])

cur.close()
conn.commit()
conn.close()
      

   

5.6 練習python操作MySQL

#!/usr/bin/env python
# coding=utf-8

import pymysql

def connectdb():
    print('連接配接到mysql伺服器...')
    # 打開資料庫連接配接
    # 使用者名:hp, 密碼:Hp12345.,使用者名和密碼需要改成你自己的mysql使用者名和密碼,并且要建立資料庫TESTDB,并在TESTDB資料庫中建立好表Student
    db = pymysql.connect("localhost","hp","Hp12345.","TESTDB")
    print('連接配接上了!')
    return db

def createtable(db):
    # 使用cursor()方法擷取操作遊标 
    cursor = db.cursor()

    # 如果存在表Sutdent先删除
    cursor.execute("DROP TABLE IF EXISTS Student")
    sql = """CREATE TABLE Student (
            ID CHAR(10) NOT NULL,
            Name CHAR(8),
            Grade INT )"""

    # 建立Sutdent表
    cursor.execute(sql)

def insertdb(db):
    # 使用cursor()方法擷取操作遊标 
    cursor = db.cursor()

    # SQL 插入語句
    sql = """INSERT INTO Student
         VALUES ('001', 'CZQ', 70),
                ('002', 'LHQ', 80),
                ('003', 'MQ', 90),
                ('004', 'WH', 80),
                ('005', 'HP', 70),
                ('006', 'YF', 66),
                ('007', 'TEST', 100)"""

    #sql = "INSERT INTO Student(ID, Name, Grade) \
    #    VALUES ('%s', '%s', '%d')" % \
    #    ('001', 'HP', 60)
    try:
        # 執行sql語句
        cursor.execute(sql)
        # 送出到資料庫執行
        db.commit()
    except:
        # Rollback in case there is any error
        print '插入資料失敗!'
        db.rollback()

def querydb(db):
    # 使用cursor()方法擷取操作遊标 
    cursor = db.cursor()

    # SQL 查詢語句
    #sql = "SELECT * FROM Student \
    #    WHERE Grade > '%d'" % (80)
    sql = "SELECT * FROM Student"
    try:
        # 執行SQL語句
        cursor.execute(sql)
        # 擷取所有記錄清單
        results = cursor.fetchall()
        for row in results:
            ID = row[0]
            Name = row[1]
            Grade = row[2]
            # 列印結果
            print "ID: %s, Name: %s, Grade: %d" % \
                (ID, Name, Grade)
    except:
        print "Error: unable to fecth data"

def deletedb(db):
    # 使用cursor()方法擷取操作遊标 
    cursor = db.cursor()

    # SQL 删除語句
    sql = "DELETE FROM Student WHERE Grade = '%d'" % (100)

    try:
       # 執行SQL語句
       cursor.execute(sql)
       # 送出修改
       db.commit()
    except:
        print '删除資料失敗!'
        # 發生錯誤時復原
        db.rollback()

def updatedb(db):
    # 使用cursor()方法擷取操作遊标 
    cursor = db.cursor()

    # SQL 更新語句
    sql = "UPDATE Student SET Grade = Grade + 3 WHERE ID = '%s'" % ('003')

    try:
        # 執行SQL語句
        cursor.execute(sql)
        # 送出到資料庫執行
        db.commit()
    except:
        print '更新資料失敗!'
        # 發生錯誤時復原
        db.rollback()

def closedb(db):
    db.close()

def main():
    db = connectdb()    # 連接配接MySQL資料庫

    createtable(db)     # 建立表
    insertdb(db)        # 插入資料
    print '\n插入資料後:'
    querydb(db) 
    deletedb(db)        # 删除資料
    print '\n删除資料後:'
    querydb(db)
    updatedb(db)        # 更新資料
    print '\n更新資料後:'
    querydb(db)

    closedb(db)         # 關閉資料庫

if __name__ == '__main__':
    main()
      

六,鞏固練習  

練習題:

        參考表結構:

            使用者類型

            使用者資訊

            權限

            使用者類型&權限

        功能:

            # 登陸、注冊、找回密碼

            # 使用者管理

            # 使用者類型

            # 權限管理

            # 配置設定權限

        特别的:程式僅一個可執行檔案

 python python操作SQLite

  SQLite是一種嵌入式資料庫,它的資料庫就是一個檔案。由于SQLite本身是C寫的,而且體積很小。是以,經常被內建到各種應用程式中,甚至在iOS 和 Android 的APP中都可以內建。

  Python就内置了SQLite3,是以在python中使用SQLite,不需要安裝任何東西,直接使用。

  在使用SQLite之前,我們先要搞清楚幾個概念:

  表是資料庫中存放關系資料的集合,一個資料庫裡面通常都包含多個表,比如學生的表,班級的表,學校的表等等。表和表之間通過外鍵關聯。

  要操作關系資料庫,首先需要連接配接到資料庫,一個資料庫連接配接成為Connection;

  連接配接到資料庫後,需要打開遊标,稱之為Cursor,通過Cursor執行SQL語句,然後獲得執行結果。

  Python定義了一套操作資料庫的API接口,任何資料庫要連接配接到Python,隻需要提供符合Python标準的資料庫驅動即可。

  由于SQLite的驅動内置在Python标準庫中,是以我們可以直接來操作SQLite資料庫。

  我們在Python互動式指令行實踐一下:

# 導入SQLite驅動:
>>> import sqlite3

# 連接配接到SQLite資料庫
# 資料庫檔案是test.db
# 如果檔案不存在,會自動在目前目錄建立:
>>> conn = sqlite3.connect('test.db')

# 建立一個Cursor:
>>> cursor = conn.cursor()

# 執行一條SQL語句,建立user表:
>>> cursor.execute('create table user (id varchar(20) primary key, name varchar(20))')
<sqlite3.Cursor object at 0x10f8aa260>

# 繼續執行一條SQL語句,插入一條記錄:
>>> cursor.execute('insert into user (id, name) values (\'1\', \'Michael\')')
<sqlite3.Cursor object at 0x10f8aa260>

# 通過rowcount獲得插入的行數:
>>> cursor.rowcount
1

# 關閉Cursor:
>>> cursor.close()

# 送出事務:
>>> conn.commit()

# 關閉Connection:
>>> conn.close()
      

  我們再試試查詢記錄:

>>> conn = sqlite3.connect('test.db')
>>> cursor = conn.cursor()

# 執行查詢語句:
>>> cursor.execute('select * from user where id=?', ('1',))
<sqlite3.Cursor object at 0x10f8aa340>

# 獲得查詢結果集:
>>> values = cursor.fetchall()
>>> values
[('1', 'Michael')]
>>> cursor.close()
>>> conn.close()
      

  使用Python的DB-API時,隻要搞清楚connection 和cursor對象,打開後一定記得關閉,就可以放心使用。

  使用cursor對象執行insert,update,delete語句時,執行結果由rowcount傳回影響的行數,就可以拿到執行結果。

  使用cursor對象執行select語句時,通過featchall() 可以拿到結果集,結果集是一個list,每個元素都是一個tuple,對應一行記錄。

  如果SQL語句帶有參數,那麼需要把參數按照位置傳遞給execute()方法,有幾個?占位符就必須對應幾個參數,例如:

ursor.execute('select * from user where name=? and pwd=?', ('abc', 'password'))      

練習:

import os, sqlite3

db_file = os.path.join(os.path.dirname(__file__), 'test.db')
print(db_file)
# E:/backup/pycode/now/ProcessDataPreprocessing/code\test.db

if os.path.isfile(db_file):
    os.remove(db_file)

# 初始化資料
conn = sqlite3.connect(db_file)
cursor = conn.cursor()
sql1 = 'create table user(id varchar(20) primary key , name varchar(20), score int)'
cursor.execute(sql1)
sql2 = "insert into user values ('001','james', 99)"
cursor.execute(sql2)

sql3 = "insert into user values ('002','durant', 99)"
cursor.execute(sql3)

cursor.close()
conn.commit()
conn.close()
      

  查詢操作:

# 查詢記錄:
conn = sqlite3.connect('test.db')
cursor = conn.cursor()
# 執行查詢語句:
sql4 = 'select * from user '
cursor.execute(sql4)
# 獲得查詢結果集:
values = cursor.fetchall()
print(values)
cursor.close()
conn.close()
      

 參考文獻:https://www.2cto.com/database/201807/761697.html

不經一番徹骨寒 怎得梅花撲鼻香

繼續閱讀