数据库
首页 > 数据库> > 使用Connector / Python连接MySQL/查询数据

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

作者:互联网

使用Connector / Python连接MySQL

connect()构造函数创建到MySQL服务器的连接并返回一个 MySQLConnection对象
在python中有以下几种方法可以连接到MySQL数据库:

import mysql.connector

cnx = mysql.connector.connect(user='scott', password='password',
                              host='127.0.0.1',
                              database='employees')
cnx.close()
from mysql.connector import (connection)

cnx = connection.MySQLConnection(user='scott', password='password',
                                 host='127.0.0.1',
                                 database='employees')
cnx.close()
import mysql.connector

config = {
  '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 errorcode

try:
  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查询数据

import datetime
import mysql.connector

cnx = 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

标签:connector,hire,name,Python,MySQL,cnx,Connector,mysql,password
来源: https://www.cnblogs.com/yuanchao-blog/p/10639132.html