Python3使用mysql.connector操作mysql数据库
2014-11-04 21:08
726 查看
一、下载与安装
下载mysql.connector:到http://dev.mysql.com/downloads/connector/python/下载并安装
二、使用
1、连接数据库
2、select查询
3、insert插入
下载mysql.connector:到http://dev.mysql.com/downloads/connector/python/下载并安装
二、使用
1、连接数据库
import mysql.connector#引入库 from mysql.connector import errorcode try: cnx = mysql.connector.connect(user='scott',password='', host='127.0.0.1', database='testt')#配置信息 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 exists") else: print(err) else: cnx.close()
2、select查询
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()
3、insert插入
import mysql.connector cnx = mysql.connector.connect(user='scott', database='employees') cursor = cnx.cursor() tomorrow = datetime.now().date() + timedelta(days=1) 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)) # 插入emploee cursor.execute(add_employee, data_employee) emp_no = cursor.lastrowid # 插入salary data_salary = { 'emp_no': emp_no, 'salary': 50000, 'from_date': tomorrow, 'to_date': date(9999, 1, 1), } cursor.execute(add_salary, data_salary) # 这里一定不要忘,必须commit提交插入 cnx.commit() cursor.close() cnx.close()
3、delete删除还有update的方法和insert类似,自己尝试一下就明白了
相关文章推荐
- python下使用mysql.connector 安装以及连接数据库的操作
- Python学习总结笔记(9)-- MySQL数据库操作之mysql-connector
- 使用MySQL connector/C++链接MySQL数据库
- 【MySql APIs】很完整的关于怎么用各种方法连接Mysql数据库,和使用API来操作Mysql数据库的资料
- 使用pymysql在python中对mysql的增删改查操作(二)
- 使用pymysql在python中对mysql的增删改查操作(五)
- 使用MySQLConnector/C++连接MySQL数据库
- 使用MySQL connector/C++链接MySQL数据库
- 使用pymysql在python中对mysql的增删改查操作(三)
- [Tips]使用 pip v1.5 安装 MySQL Connector/Python
- VC6.0操作mysql数据库使用添加 libmysql.lib 的方法
- Programming Multiplayer Game - 使用Mysql++操作MySQL数据库
- Python使用MySQLdb操作MySQL
- 使用pymysql在python中对mysql的增删改查操作(四)
- python文件读写并使用mysql批量插入示例分享(python操作mysql)
- 使用MySQL connector/C++链接MySQL数据库
- 编写操作数据库的JAVA程序时需要的连接MySQL数据库的JDBC连接包mysql-connector-java-5.1.10.zip怎么安装
- 使用MySQL connector/C++链接MySQL数据库
- 使用Python操作MySQL
- 【python学习.Mysql的基本操作使用】