python python操做MySQL

  MySQL是Web世界中使用最普遍的數據庫服務器,SQLite的特定是輕量級,可嵌入,但不能承受高併發訪問,適合桌面和移動應用。而MySQL是爲服務器端設計的數據庫,能承受高併發訪問,同時佔用的內存也遠遠大於SQLite。此外,MySQL內部有多種數據庫引擎,最經常使用的引擎是支持數據庫事務的InnoDB。html

一,安裝MySQL

這裏小編就不詳細介紹了,要是有不會安裝的能夠參考下面博客python

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

二,安裝MySQL-python

要想使python能夠操做mysql 就須要MySQL-python驅動,它是python 操做mysql必不可少的模塊。sql

下載地址: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下完成的。)高併發

沒有報錯提示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數據庫的流程:

 

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

三、獲取查詢數據

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') # 相對絕對位置移動

四、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

相關文章
相關標籤/搜索