日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 运维知识 > 数据库 >内容正文

数据库

使用Connector / Python连接MySQL/查询数据

發(fā)布時間:2023/12/13 数据库 31 豆豆
生活随笔 收集整理的這篇文章主要介紹了 使用Connector / Python连接MySQL/查询数据 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

使用Connector / Python連接MySQL

connect()構(gòu)造函數(shù)創(chuàng)建到MySQL服務(wù)器的連接并返回一個 MySQLConnection對象
在python中有以下幾種方法可以連接到MySQL數(shù)據(jù)庫:

  • 1.使用connect()構(gòu)造函數(shù)
import mysql.connectorcnx = mysql.connector.connect(user='scott', password='password',host='127.0.0.1',database='employees') cnx.close()
  • 使用connection.MySQLConnection() 類創(chuàng)建連接對象
from mysql.connector import (connection)cnx = connection.MySQLConnection(user='scott', password='password',host='127.0.0.1',database='employees') cnx.close()
  • 在字典中定義連接參數(shù)并使用 **運算符
import mysql.connectorconfig = {'user': 'scott','password': 'password','host': '127.0.0.1','database': 'employees','raise_on_warnings': True }cnx = mysql.connector.connect(**config)cnx.close()

處理鏈接錯誤使用try語句并使用error.Error異常捕獲所有錯誤

import mysql.connector from mysql.connector import errorcodetry:cnx = mysql.connector.connect(user='scott',database='employ') except mysql.connector.Error as err:if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:print("Something is wrong with your user name or password")elif err.errno == errorcode.ER_BAD_DB_ERROR:print("Database does not exist")else:print(err) else:cnx.close()

2.使用Connector / Python查詢數(shù)據(jù)

import datetime import mysql.connectorcnx = mysql.connector.connect(user='scott', database='employees') 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()

參考鏈接:

https://dev.mysql.com/doc/connector-python/en/connector-python-examples.html

轉(zhuǎn)載于:https://www.cnblogs.com/yuanchao-blog/p/10639132.html

總結(jié)

以上是生活随笔為你收集整理的使用Connector / Python连接MySQL/查询数据的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。