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()

connector for python实验的更多相关文章

  1. python 实验环境

    python 实验环境的搭建 刚开始在windows环境下尝试过komodo ,eclispse pydev,swing,spyder甚至limodou的编辑器,之后ipython,安装很多科学计算包 ...

  2. Frenetic Python实验(三)

    实验5 repeater 这个实验在HelloSDNWorld里面做的实验是一样的.HelloSDNWorld 目的:模拟一个有多个端口的中继器. This application implement ...

  3. Frenetic Python实验(二)

    实验3 packet_in_out 目的:模拟一个普通的双端口中继器. This application implements a very simple 2 port repeater where ...

  4. Frenetic Python实验(一)

    Follow: Github-Frenetic 准备: 所有的实验,第一步都需要开启控制器,命令: $ frenetic http-controller --verbosity debug 每一个实验 ...

  5. Connector for Python

    连接mysql, 需要mysql connector, conntector是一种驱动程序,python连接mysql的驱动程序,mysql官方给出的名称为connector/python, 可参考m ...

  6. Python实验案例

    Python 运算符.内置函数 实验目的: 1.熟练运用 Python 运算符. 2.熟练运用 Python 内置函数.实验内容: 1.编写程序,输入任意大的自然数,输出各位数字之和. 2.编写程序, ...

  7. python实验一

    安徽工程大学 Python程序设计实验报告 班级物流管理191 姓名彭艺    学号3190505139成绩          日期  2020年3月3日     指导老师    修宇 实验名称    ...

  8. Python实验报告——第4章 序列的应用

    实验报告 [实验目的] 1.掌握python中序列及序列的常用操作. 2.根据实际需要选择使用合适的序列类型. [实验条件] 1.PC机或者远程编程环境. [实验内容] 1.完成第四章 序列的应用 实 ...

  9. Python实验报告——第3章 流程控制语句

    实验报告 [实验目的] 1.掌握python中流程控制语句的使用,并能够应用到实际开发中. [实验条件] 1.PC机或者远程编程环境 [实验内容] 1.完成第三章流程控制语句实例01-09,实战一到实 ...

随机推荐

  1. 修改elementui默认样式

    转发连接:https://blog.csdn.net/weixin_41557291/article/details/80606525 在需要更改的组件里新增一个style标签[重点:不要加scope ...

  2. Django 2.0 官方文档翻译

    from django.contrib import admin from django.urls import include, path urlpatterns = [ path('polls/' ...

  3. 【干货】提取图片元数据之exiftool

    知识源:UC3Mx: INF.2x网络安全基础:实践方法 课程  第1周.讲座2.计算机取证  常见的法医痕迹  2.2.1.元数据 exiftool是一种查看,更新或删除元数据的工具.是Window ...

  4. Mongodb 相关链接

    http://www.cnblogs.com/lanceyan/tag/mongodb/

  5. 使用chrome开发者工具中的performance面板解决性能瓶颈

    前面的话 使用Chrome DevTools的performance面板可以记录和分析页面在运行时的所有活动.本文将详细介绍如何使用performance面板解决性能瓶颈 准备 [匿名模式] 匿名模式 ...

  6. SpringBoot 上传文件夹

    前端代码: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF ...

  7. jsp参数乱码解决

    iframe src引入jsp,?跟着的中文参数会乱码 解决方法: var CJJG=encodeURI(encodeURI(value.data.CJJG));//js里面转码一次 //jsp页面里 ...

  8. OpenCV-Python : 直方图

    啥叫直方图 直方图简单来说就是图像中每个像素值的个数统计,比如一副灰度图中像素值为0的有多少个,1的有多少个... 在计算直方图之前,先了解几个术语: dims:要计算的通道数,对于灰度图dims=1 ...

  9. Zabbix(二)

    zabbix 监控第一台服务器 https://blog.51cto.com/5001660/2136303 一.搭建一台测试服务器 1.安装一台centos7操作系统 配置网络: vim /etc/ ...

  10. PHP微信商户支付 - 企业付款到零钱功能(即提现)技术资料汇总

    PHP实现微信开发中提现功能(企业付款到用户零钱) 一.实现该功能目的 这几天在小程序里要实现用户从系统中提现到零钱的功能,查了一下文档可以使用 企业付款到用户零钱 来实现: 官方文档:https:/ ...