Python MySQL 數據庫鏈接不一樣方式

PyMySQL 驅動鏈接python

什麼是 PyMySQL?
PyMySQL 是在 Python3.x 版本中用於鏈接 MySQL 服務器的一個庫,Python2中則使用mysqldb。mysql

PyMySQL 遵循 Python 數據庫 API v2.0 規範,幷包含了 pure-Python MySQL 客戶端庫。git

PyMySQL 安裝
在使用 PyMySQL 以前,咱們須要確保 PyMySQL 已安裝。github

PyMySQL 下載地址:https://github.com/PyMySQL/PyMySQL。sql

若是還未安裝,咱們可使用如下命令安裝最新版的 PyMySQL:數據庫

$ pip3 install PyMySQL
若是你的系統不支持 pip 命令,可使用如下方式安裝:django

一、使用 git 命令下載安裝包安裝(你也能夠手動下載):python3.x

$ git clone https://github.com/PyMySQL/PyMySQL
$ cd PyMySQL/
$ python3 setup.py install
二、若是須要制定版本號,可使用 curl 命令來安裝:服務器

$ # X.X 爲 PyMySQL 的版本號
$ curl -L https://github.com/PyMySQL/PyMySQL/tarball/pymysql-X.X | tar xz
$ cd PyMySQL*
$ python3 setup.py install
$ # 如今你能夠刪除 PyMySQL* 目錄
注意:請確保您有root權限來安裝上述模塊。網絡

實例:
如下實例連接 Mysql 的 TESTDB 數據庫:

實例(Python 3.0+)
#!/usr/bin/python3

import pymysql

# 打開數據庫鏈接
db = pymysql.connect("localhost","testuser","test123","TESTDB" )

# 使用 cursor() 方法建立一個遊標對象 cursor
cursor = db.cursor()

# 使用 execute() 方法執行 SQL 查詢
cursor.execute("SELECT VERSION()")

# 使用 fetchone() 方法獲取單條數據.
data = cursor.fetchone()

print ("Database version : %s " % data)

# 關閉數據庫鏈接
db.close()

mysql-connector 驅動

mysql-connector 是 MySQL 官方提供的驅動器。

咱們可使用 pip 命令來安裝 mysql-connector:

python -m pip install mysql-connector
使用如下代碼測試 mysql-connector 是否安裝成功:

demo_mysql_test.py:
import mysql.connector
執行以上代碼,若是沒有產生錯誤,代表安裝成功。

建立數據庫鏈接
可使用如下代碼來鏈接數據庫:

demo_mysql_test.py:
import mysql.connector

mydb = mysql.connector.connect(
host="localhost", # 數據庫主機地址
user="yourusername", # 數據庫用戶名
passwd="yourpassword" # 數據庫密碼
)

print(mydb)

MySQLdb庫來鏈接

MySQLdb先支持Python2.,不支持Python3.。

MySQLdb的安裝
MySQLdb的安裝可使用pip進行安裝:

pip install MySQL-python==1.2.5

Python對MySQL進行操做
Python與MySQL進行鏈接-connection
建立鏈接的對象,創建Python客戶端與數據庫網絡鏈接
建立的基本方法MySQLdb.connect(相關的參數),其中的主要參數有(host, user, passwd, port, db, charset),在這些參數中,只有port是數字類型,其餘的參數都是字符串類型。
對數據庫進行執行,獲取執行的結構-cursor
遊標對象:用於執行查詢和獲取結果
cursor對象包含的方法以下:
參數名 說明
execute(command) 執行一個數據庫查詢和命令
fetchone() 獲取結果集中的下一行
fetchmany() 獲取結果集中的下幾行
fetchall() 獲取結果集中的所有信息
rowcount 最近的一次execute返回數據或影響的行數
close() 關閉遊標對象
舉一個例子

import MySQLdb
conn = MySQLdb.Connect(
host = "127.0.0.1",
port = 3306,
user = "lee",
passwd = "123",
db = "lee",
charset = "utf8",
)

cursor = conn.cursor()

sql_command = 'select * from user'

cursor.execute(sql_command)

rs = cursor.fetchall()


for ele in rs:
print 'userid : %d , username : %s' %ele

cursor.close()
conn.close()

讓python 3支持mysqldb的解決方法

緣由
MySQLdb 只適用於python2.x,發現pip裝不上。它在py3的替代品是: import pymysql

pip install pymysql
django+mysql
而Django默認的仍是使用MySQLdb:執行會報:ImportError: No module named 'MySQLdb'

解決:
在站點的 __init__.py 文件中添加

import pymysql
pymysql.install_as_MySQLdb()

在使用torndb的過程當中發現其底層是對MySQLdb的封裝,而MySQLdb不支持python3.x
解決:安裝mysqlclient包,其徹底兼容MySQLdb
pip install mysqlclient

解決了MySQLdb問題後,使用torndb的query功能是報了新的錯誤,以下:


AttributeError: module 'itertools' has no attribute 'izip'


源代碼:

#! /usr/bin env python3
# -*- coding:utf-8 -*-

import torndb

config = {
"host": "127.0.0.1:3306",
"user": "root",
"password": "bukeshuo",
"database": "db_test"
}
def query_all():
con = torndb.Connection(**config)
results = con.query('select account from users')
con.close()
return results

print(query_all())

 

解決方案:更改con.query()中的源代碼。(按住ctrl點擊con.query 目的是找到這個模塊的源代碼)
按照下面的提示進行更改,並保存。

def query(self, query, *parameters, **kwparameters): """Returns a row list for the given query and parameters.""" cursor = self._cursor() try: self._execute(cursor, query, parameters, kwparameters) column_names = [d[0] for d in cursor.description] """ 錯誤說itertools找不到izip模塊。 由於咱們使用的mysqlclient替代MySQLdb, 因此使用zip_longest模塊替代izip模塊。 """ # 使用這一句替代下面一行代碼 # return [Row(itertools.zip_longest(column_names, row)) for row in cursor] return [Row(itertools.izip(column_names, row)) for row in cursor] finally: cursor.close()

相關文章
相關標籤/搜索