下文給大家?guī)?lái)安裝mysql-connector-python的詳細(xì)步驟有關(guān)內(nèi)容,相信大家一定看過(guò)類(lèi)似的文章。我們給大家?guī)?lái)的有何不同呢?一起來(lái)看看正文部分吧,相信看完安裝mysql-connector-python的詳細(xì)步驟你一定會(huì)有所收獲。
創(chuàng)新互聯(lián)于2013年創(chuàng)立,是專(zhuān)業(yè)互聯(lián)網(wǎng)技術(shù)服務(wù)公司,擁有項(xiàng)目成都網(wǎng)站制作、成都做網(wǎng)站網(wǎng)站策劃,項(xiàng)目實(shí)施與項(xiàng)目整合能力。我們以讓每一個(gè)夢(mèng)想脫穎而出為使命,1280元江海做網(wǎng)站,已為上家服務(wù),為江海各地企業(yè)和個(gè)人服務(wù),聯(lián)系電話:028-86922220什么是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.
簡(jiǎn)單來(lái)說(shuō)就是Python用來(lái)連接并訪問(wèn)MySQL的第三方庫(kù);
安裝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要寫(xiě)成tuple類(lèi)型,第二種data_salary要寫(xiě)成字典類(lèi)型 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()
查詢(xún)數(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
對(duì)于上文關(guān)于安裝mysql-connector-python的詳細(xì)步驟,大家覺(jué)得是自己想要的嗎?如果想要了解更多相關(guān),可以繼續(xù)關(guān)注我們的行業(yè)資訊板塊。
另外有需要云服務(wù)器可以了解下創(chuàng)新互聯(lián)cdcxhl.cn,海內(nèi)外云服務(wù)器15元起步,三天無(wú)理由+7*72小時(shí)售后在線,公司持有idc許可證,提供“云服務(wù)器、裸金屬服務(wù)器、高防服務(wù)器、香港服務(wù)器、美國(guó)服務(wù)器、虛擬主機(jī)、免備案服務(wù)器”等云主機(jī)租用服務(wù)以及企業(yè)上云的綜合解決方案,具有“安全穩(wěn)定、簡(jiǎn)單易用、服務(wù)可用性高、性?xún)r(jià)比高”等特點(diǎn)與優(yōu)勢(shì),專(zhuān)為企業(yè)上云打造定制,能夠滿(mǎn)足用戶(hù)豐富、多元化的應(yīng)用場(chǎng)景需求。