使用Connector / Python连接MySQL/查询数据
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了使用Connector / Python连接MySQL/查询数据,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1807字,纯文字阅读大概需要3分钟。
内容图文
使用Connector / Python连接MySQL
connect()构造函数创建到MySQL服务器的连接并返回一个 MySQLConnection对象
在python中有以下几种方法可以连接到MySQL数据库:
- 1.使用connect()构造函数
import mysql.connector
cnx = mysql.connector.connect(user='scott', password='password',
host='127.0.0.1',
database='employees')
cnx.close()
- 使用connection.MySQLConnection() 类创建连接对象
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 / Python连接MySQL/查询数据全部内容,希望文章能够帮你解决使用Connector / Python连接MySQL/查询数据所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。