请被人做网站,wordpress图片 高清,永久免费生成app网页,sem推广优化使用Connector / Python连接MySQLconnect()构造函数创建到MySQL服务器的连接并返回一个 MySQLConnection对象在python中有以下几种方法可以连接到MySQL数据库#xff1a;1.使用connect()构造函数import mysql.connectorcnx mysql.connector.connect(userscott, passwordpassw…使用Connector / Python连接MySQLconnect()构造函数创建到MySQL服务器的连接并返回一个 MySQLConnection对象在python中有以下几种方法可以连接到MySQL数据库1.使用connect()构造函数import mysql.connectorcnx mysql.connector.connect(userscott, passwordpassword,host127.0.0.1,databaseemployees)cnx.close()使用connection.MySQLConnection() 类创建连接对象from mysql.connector import (connection)cnx connection.MySQLConnection(userscott, passwordpassword,host127.0.0.1,databaseemployees)cnx.close()在字典中定义连接参数并使用 **运算符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.connectorfrom mysql.connector import errorcodetry:cnx mysql.connector.connect(userscott,databaseemploy)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 datetimeimport mysql.connectorcnx mysql.connector.connect(userscott, databaseemployees)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()参考链接