安裝mysql-connector-python的詳細(xì)步驟

下文給大家?guī)戆惭bMySQL-connector-python的詳細(xì)步驟有關(guān)內(nèi)容,相信大家一定看過類似的文章。我們給大家?guī)淼挠泻尾煌??一起來看看正文部分吧,相信看完安裝mysql-connector-python的詳細(xì)步驟你一定會(huì)有所收獲。

創(chuàng)新互聯(lián)專注于寧洱網(wǎng)站建設(shè)服務(wù)及定制,我們擁有豐富的企業(yè)做網(wǎng)站經(jīng)驗(yàn)。 熱誠為您提供寧洱營銷型網(wǎng)站建設(shè),寧洱網(wǎng)站制作、寧洱網(wǎng)頁設(shè)計(jì)、寧洱網(wǎng)站官網(wǎng)定制、微信平臺(tái)小程序開發(fā)服務(wù),打造寧洱網(wǎng)絡(luò)公司原創(chuàng)品牌,更為您提供寧洱網(wǎng)站排名全網(wǎng)營銷落地服務(wù)。

什么是MySQL Connector/Python?

MySQL Connector/Python enables Python programs to access MySQL databases, using an API that is compliant with the Python Database API Specification v2.0 (PEP 249). It is written in pure Python and does not have any dependencies except for the Python Standard Library.

簡單來說就是Python用來連接并訪問MySQL的第三方庫;

安裝mysql-connector-python

sht-sgmhadoopcm-01.telenav.cn:mysqladmin:/usr/local/virtualenv/test1_env:>source test1_env/bin/activate

(test1_env) sht-sgmhadoopcm-01.telenav.cn:mysqladmin:/usr/local/virtualenv/test1_env:>pip install mysql-connector-python

(test1_env) [root@sht-sgmhadoopcm-01 software]# pip list|grep mysql

mysql-connector-python 8.0.15

檢查安裝是否成功

(test1_env) [root@sht-sgmhadoopcm-01 software]# ls -ltrh test1_env/lib/python2.7/site-packages/mysql_connector_python-8.0.15.dist-info/

total 124K

-rw-r--r-- 1 root root  105 Feb 13 00:04 WHEEL

-rw-r--r-- 1 root root 1.5K Feb 13 00:04 METADATA

-rw-r--r-- 1 root root  94K Feb 13 00:04 LICENSE.txt

-rw-r--r-- 1 root root   40 Feb 13 00:04 top_level.txt

-rw-r--r-- 1 root root    4 Feb 13 00:04 INSTALLER

-rw-r--r-- 1 root root 8.4K Feb 13 00:04 RECORD

>>> from distutils.sysconfig import get_python_lib

>>> print get_python_lib()

/opt/software/test1_env/lib/python2.7/site-packages

連接MySQL

方法1: connect()

import mysql.connector
cnx = mysql.connector.connect(user='root', password='agm43gadsg',
                              host='172.16.101.54',port='3306',
                              database='testdb')
cnx.close()

方法2:MySQLConnection()

from mysql.connector import (connection)
cnx = connection.MySQLConnection(user='root', password='agm43gadsg',
                              host='172.16.101.54',port='3306',
                              database='testdb')
cnx.close()

方法3:配置文件

import mysql.connector
config = {
  'user': 'root',
  'password': 'agm43gadsg',
  'host': '172.16.101.54',
  'port': '3306',
  'database': 'testdb'
}
cnx = mysql.connector.connect(**config)
cnx.close()

創(chuàng)建表

from __future__ import print_function
import mysql.connector
from mysql.connector import errorcode

DB_NAME = 'testdb2'
TABLES = {}
TABLES['employees'] = (
    "CREATE TABLE `employees` ("
    "  `emp_no` int(11) NOT NULL AUTO_INCREMENT,"
    "  `birth_date` date NOT NULL,"
    "  `first_name` varchar(14) NOT NULL,"
    "  `last_name` varchar(16) NOT NULL,"
    "  `gender` enum('M','F') NOT NULL,"
    "  `hire_date` date NOT NULL,"
    "  PRIMARY KEY (`emp_no`)"
    ") ENGINE=InnoDB")
TABLES['departments'] = (
    "CREATE TABLE `departments` ("
    "  `dept_no` char(4) NOT NULL,"
    "  `dept_name` varchar(40) NOT NULL,"
    "  PRIMARY KEY (`dept_no`), UNIQUE KEY `dept_name` (`dept_name`)"
    ") ENGINE=InnoDB")
TABLES['salaries'] = (
    "CREATE TABLE `salaries` ("
    "  `emp_no` int(11) NOT NULL,"
    "  `salary` int(11) NOT NULL,"
    "  `from_date` date NOT NULL,"
    "  `to_date` date NOT NULL,"
    "  PRIMARY KEY (`emp_no`,`from_date`), KEY `emp_no` (`emp_no`),"
    "  CONSTRAINT `salaries_ibfk_1` FOREIGN KEY (`emp_no`) "
    "     REFERENCES `employees` (`emp_no`) ON DELETE CASCADE"
    ") ENGINE=InnoDB")
TABLES['dept_emp'] = (
    "CREATE TABLE `dept_emp` ("
    "  `emp_no` int(11) NOT NULL,"
    "  `dept_no` char(4) NOT NULL,"
    "  `from_date` date NOT NULL,"
    "  `to_date` date NOT NULL,"
    "  PRIMARY KEY (`emp_no`,`dept_no`), KEY `emp_no` (`emp_no`),"
    "  KEY `dept_no` (`dept_no`),"
    "  CONSTRAINT `dept_emp_ibfk_1` FOREIGN KEY (`emp_no`) "
    "     REFERENCES `employees` (`emp_no`) ON DELETE CASCADE,"
    "  CONSTRAINT `dept_emp_ibfk_2` FOREIGN KEY (`dept_no`) "
    "     REFERENCES `departments` (`dept_no`) ON DELETE CASCADE"
    ") ENGINE=InnoDB")
TABLES['dept_manager'] = (
    "  CREATE TABLE `dept_manager` ("
    "  `dept_no` char(4) NOT NULL,"
    "  `emp_no` int(11) NOT NULL,"
    "  `from_date` date NOT NULL,"
    "  `to_date` date NOT NULL,"
    "  PRIMARY KEY (`emp_no`,`dept_no`),"
    "  KEY `emp_no` (`emp_no`),"
    "  KEY `dept_no` (`dept_no`),"
    "  CONSTRAINT `dept_manager_ibfk_1` FOREIGN KEY (`emp_no`) "
    "     REFERENCES `employees` (`emp_no`) ON DELETE CASCADE,"
    "  CONSTRAINT `dept_manager_ibfk_2` FOREIGN KEY (`dept_no`) "
    "     REFERENCES `departments` (`dept_no`) ON DELETE CASCADE"
    ") ENGINE=InnoDB")
TABLES['titles'] = (
    "CREATE TABLE `titles` ("
    "  `emp_no` int(11) NOT NULL,"
    "  `title` varchar(50) NOT NULL,"
    "  `from_date` date NOT NULL,"
    "  `to_date` date DEFAULT NULL,"
    "  PRIMARY KEY (`emp_no`,`title`,`from_date`), KEY `emp_no` (`emp_no`),"
    "  CONSTRAINT `titles_ibfk_1` FOREIGN KEY (`emp_no`)"
    "     REFERENCES `employees` (`emp_no`) ON DELETE CASCADE"
    ") ENGINE=InnoDB")
    
cnx = mysql.connector.connect(user='root', password='agm43gadsg', host='172.16.101.54',port='3306', database='testdb')
cursor = cnx.cursor()
def create_database(cursor):
    try:
        cursor.execute("CREATE DATABASE {} DEFAULT CHARACTER SET 'utf8'".format(DB_NAME))
    except mysql.connector.Error as err:
        print("Failed creating database: {}".format(err))
        exit(1)
try:
    cursor.execute("USE {}".format(DB_NAME))
except mysql.connector.Error as err:
    print("Database {} does not exists.".format(DB_NAME))
    if err.errno == errorcode.ER_BAD_DB_ERROR:
        create_database(cursor)
        print("Database {} created successfully.".format(DB_NAME))
        cnx.database = DB_NAME
    else:
        print(err)
        exit(1)
        
for table_name in TABLES:
    table_description = TABLES[table_name]
    try:
        print("Creating table {}: ".format(table_name), end='')
        cursor.execute(table_description)
    except mysql.connector.Error as err:
        if err.errno == errorcode.ER_TABLE_EXISTS_ERROR:
            print("already exists.")
        else:
            print(err.msg)
    else:
        print("OK")
cursor.close()
cnx.close()

插入數(shù)據(jù)

from __future__ import print_function
from datetime import date, datetime, timedelta
import mysql.connector
cnx = mysql.connector.connect(user='root', password='agm43gadsg', host='172.16.101.54',port='3306', database='testdb')
cursor = cnx.cursor()
tomorrow = datetime.now().date() + timedelta(days=1)

#下面是兩種格式的insert,第一種data_employee要寫成tuple類型,第二種data_salary要寫成字典類型
add_employee = ("INSERT INTO employees "
"(first_name, last_name, hire_date, gender, birth_date) "
"VALUES (%s, %s, %s, %s, %s)")

add_salary = ("INSERT INTO salaries "
"(emp_no, salary, from_date, to_date) "
"VALUES (%(emp_no)s, %(salary)s, %(from_date)s, %(to_date)s)")

data_employee = ('Geert', 'Vanderkelen', tomorrow, 'M', date(1977, 6, 14))

cursor.execute(add_employee, data_employee)
emp_no = cursor.lastrowid #打印最后一次插入emp_no列值,作為salaries表的emp_no列值,要求employees表的emp_no必須是自增主鍵才行,

data_salary = {
'emp_no': emp_no,
'salary': 50000,
'from_date': tomorrow,
'to_date': date(9999, 1, 1),
}

cursor.execute(add_salary, data_salary)
cnx.commit()
cursor.close()
cnx.close()

查詢數(shù)據(jù)

import datetime
import mysql.connector

cnx = mysql.connector.connect(user='root', password='agm43gadsg', host='172.16.101.54',port='3306', database='testdb')
cursor = cnx.cursor()
query = ("SELECT first_name, last_name, hire_date FROM employees "
"WHERE hire_date BETWEEN %s AND %s")

hire_start = datetime.date(1999, 1, 1)
hire_end = datetime.date(1999, 12, 31)

cursor.execute(query, (hire_start, hire_end))

for (first_name, last_name, hire_date) in cursor:
print("{}, {} was hired on {:%d %b %Y}".format(last_name, first_name, hire_date))

cursor.close()
cnx.close()

MySQL Connector/Python

對于上文關(guān)于安裝mysql-connector-python的詳細(xì)步驟,大家覺得是自己想要的嗎?如果想要了解更多相關(guān),可以繼續(xù)關(guān)注我們的行業(yè)資訊板塊。

名稱欄目:安裝mysql-connector-python的詳細(xì)步驟
網(wǎng)頁地址:http://muchs.cn/article46/pihdeg.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供網(wǎng)站設(shè)計(jì)公司、外貿(mào)建站、網(wǎng)站建設(shè)網(wǎng)站營銷、品牌網(wǎng)站設(shè)計(jì)網(wǎng)站收錄

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)

成都做網(wǎng)站