MySQL 是最流行的关系型数据库管理系统,如果你不熟悉 MySQL,可以阅读 MySQL 教程。

下面为大家介绍使用 mysql-connector 来连接使用 MySQL, mysql-connector 是 MySQL 官方提供的驱动器。

我们可以使用 pip 命令来安装 mysql-connector:

python -m pip install mysql-connector

使用以下代码测试 mysql-connector 是否安装成功:

import mysql.connector

执行以上代码,如果没有产生错误,表明安装成功。

1、数据库连接

连接数据库的代码如下

 代码如下 复制代码
import mysql.connector
config={'host':'127.0.0.1',#默认127.0.0.1
        'user':'root',
        'password':'123456',
        'port':3306 ,#默认即为3306
        'database':'test',
        'charset':'utf8'#默认即为utf8
        }
try:
  cnn=mysql.connector.connect(**config)
except mysql.connector.Error as e:
  print('connect fails!{}'.format(e))

连接方法上和MySQLdb模块略有不同。MySQLdb使用的是=号,这里使用的是 : 号。

2、创建表

下面我们根据上面新建的一个数据库连接创建一张名为student的表:

 代码如下 复制代码
sql_create_table='CREATE TABLE `student` \
(`id` int(10) NOT NULL AUTO_INCREMENT,\
`name` varchar(10) DEFAULT NULL,\
`age` int(3) DEFAULT NULL,\
PRIMARY KEY (`id`)) \
ENGINE=MyISAM DEFAULT CHARSET=utf8'
cursor=cnn.cursor()
try:
  cursor.execute(sql_create_table)
except mysql.connector.Error as e:
  print('create table orange fails!{}'.format(e)) 

3、插入数据

插入数据的语法上和MySQLdb上基本上是一样的:

 代码如下 复制代码
cursor=cnn.cursor()
try:
  '第一种:直接字符串插入方式'
  sql_insert1="insert into student (name, age) values ('orange', 20)"
  cursor.execute(sql_insert1)
  '第二种:元组连接插入方式'
  sql_insert2="insert into student (name, age) values (%s, %s)"
  #此处的%s为占位符,而不是格式化字符串,所以age用%s
  data=('shiki',25)
  cursor.execute(sql_insert2,data)
  '第三种:字典连接插入方式'
  sql_insert3="insert into student (name, age) values (%(name)s, %(age)s)"
  data={'name':'mumu','age':30}
  cursor.execute(sql_insert3,data)
  #如果数据库引擎为Innodb,执行完成后需执行cnn.commit()进行事务提交
except mysql.connector.Error as e:
  print('insert datas error!{}'.format(e))
finally:
  cursor.close()
  cnn.close()

同样,MySQL Connector也支持多次插入,同样其使用的也是cursor.executemany,示例如下:

 代码如下 复制代码
stmt='insert into student (name, age) values (%s,%s)'
data=[
     ('Lucy',21),
     ('Tom',22),
     ('Lily',21)]
cursor.executemany(stmt,data)

4、查询操作

 代码如下 复制代码
cursor=cnn.cursor()
try:
  sql_query='select id,name from student where  age > %s'
  cursor.execute(sql_query,(21,))
  for id,name in cursor:
    print ('%s\'s age is older than 25,and her/his id is %d'%(name,id))
except mysql.connector.Error as e:
  print('query error!{}'.format(e))
finally:
  cursor.close()
  cnn.close()

5、删除操作

 代码如下 复制代码

cursor=cnn.cursor()
try:
  sql_delete='delete from student where name = %(name)s and age < %(age)s'
  data={'name':'orange','age':24}
  cursor.execute(sql_delete,data)
except mysql.connector.Error as e:
  print('delete error!{}'.format(e))
finally:
  cursor.close()
  cnn.close()

转载于:https://www.cnblogs.com/wsxzl/p/10721296.html

Connector for Python相关推荐

  1. python访问数据库

    1. python DB api简介 python DB api python访问数据库的统一接口规范,详细可参考https://www.python.org/dev/peps/pep-0249/ p ...

  2. Python著名的lib和开发框架(均为转载)

    第一,https://github.com/vinta/awesome-python Awesome Python A curated list of awesome Python framework ...

  3. Python资源列表-Awesome Python,收藏吧,基本全了

    记得当初学C/C++,留下的深刻印象就是严肃.谨慎,特别关注功能函数实现,写代码前会经常看书,怕自己犯低级又不可知的错误,像那些经典<C和指针>.<C缺陷和陷阱>.<编程 ...

  4. c语言无法打开源文件stdafx.h,vs2010 中无法打开 源文件 stdafx.h 未定义标识符 “xxx”...

    HDU 1231 (13.12.2) Problem Description 给定K个整数的序列{ N1, N2, ..., NK },其任意连续子序列可表示为{ Ni, Ni+1, ..., Nj ...

  5. MYSQL服务3306端口_无法连接到'localhost:3306'上的mysql服务器,即使mysqld正在3306端口上运行...

    尝试使用mysql connector通过python连接到mysql,但出现以下错误: Traceback (most recent call last): File "/var/www/ ...

  6. mysql connector python linux_MySQL Connector/Python 安装、测试

    安装Connector/Python: # wget http://cdn.mysql.com/Downloads/Connector-Python/mysql-connector-python-1. ...

  7. python解析数据包时出现问题_MySQL Connector / Python InterfaceError:“解析EOF数据包失败”...

    据我所知,我已经安装了MySQL Connector / Python(v1.2.3)模块没有问题 . 这是在CentOS 5.4上使用Python 2.7.7(Anaconda发行版,尽管在vani ...

  8. django mysql connector_MySQL Connector / Python作为Django引擎?

    即使经过数小时和数小时的谷歌搜索,也无法找到答案.搜索堆栈溢出.我向你们保证,我已经看到了所有可能被视为相关的答案,但这些答案都没有解决我所面临的问题.无需再费周折 – 目前在shell中我可以这样做 ...

  9. mysql connector python linux_Python使用mysql.connector链接mysql数据库

    之前一直使用pythond mysqldb链接数据库,随着mysql被oracle收购之后,我发现mysqldb就不怎么更新了. 现在开始使用oracle提供的mysql.connector来操作my ...

最新文章

  1. windows建立PPPoE服务器
  2. YARN-2.7.3-源码分析系列2:启动脚本原理的分析
  3. 判断控件是否出现了滚动条
  4. 一站式学习Wireshark(一):Wireshark基本用法
  5. php redis管道,php redis pipeline怎么用 - 翟码农技术博客
  6. matplotlib绘图入门详解
  7. 与VS集成的若干种代码生成解决方案[博文汇总(共8篇)]
  8. CentOS 7/8 安装 oniguruma 和 oniguruma-devel
  9. 怎么调用系统通讯录并向被选中联系人发送短信
  10. 网站开启Gzip压缩-apache
  11. npcap关闭_npcap是什么软件
  12. 【语义分割】Smoothed Dilated Convolutions for Improved Dense Prediction阅读笔记
  13. dategurd oracle_Oracle Data Guard
  14. Tilera 服务器上OpenJDK的安装尝试
  15. ps3本服务器维修,ps3端ftp服务器
  16. FZU1892接水管游戏-BFS加上简单的状态压缩和位运算处理
  17. 地图经纬度坐标转换BD-09/GCJ-02/WGS84坐标转换
  18. js数字输入的验证~
  19. 联想笔记本桌面计算机不见了,桌面上的图标不见了怎么办,教您桌面上的图标不见了怎么办...
  20. 12.27追求世俗意义上的成功与心灵快感的矛盾

热门文章

  1. SAP QM 稳定性研究功能研习系列1 - 稳定性研究总流程
  2. 如果神经网络规模足够大,会产生智能吗?
  3. 强化学习AI:它菜了,我慌了
  4. BERT在小米NLP业务中的实战探索
  5. 安防行业巨头都是如何布局无人机的?
  6. 说AI没有创造性?现在它都能创作鬼畜音乐了
  7. 「AI初识境」深度学习模型中的Normalization,你懂了多少?
  8. 他为何能够领跑互联网与AI时代?李彦宏讲述成功之道
  9. 2018年终总结之摄影作品展
  10. 系统学习NLP(三)--NLP入门综述