MySQL Connector/Python 是 MySQL 官方提供的 Python 连接 MySQL 数据库的驱动程序了,很多初学者对于 在python中连接mysql数据库还是有点为难了,下文我们只需要了解这个MySQLConnector模块问题就可以解决了。相较于MySQLdb模块来说,其支持python3,而MySQLdb目前只支持到python2.7版本。这里就结合示例,总结下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()

Python中的MySQLConnector使用介绍的更多相关文章

  1. python中multiprocessing.pool函数介绍_正在拉磨_新浪博客

    python中multiprocessing.pool函数介绍_正在拉磨_新浪博客     python中multiprocessing.pool函数介绍    (2010-06-10 03:46:5 ...

  2. [转载]python中multiprocessing.pool函数介绍

    原文地址:http://blog.sina.com.cn/s/blog_5fa432b40101kwpi.html 作者:龙峰 摘自:http://hi.baidu.com/xjtukanif/blo ...

  3. Python中关于函数的介绍

    一.什么是函数       当我们在日常工作中编写代码时,有没有发现这种情况,写了一套代码,却发现里面有很多段代码出现了有规律的重复,这样就不符合一个合格程序员的标准了,一个合格的程序员编写的代码最重 ...

  4. Python中__new__与__init__介绍

    在python2.x中,从object继承得来的类称为新式类(如class A(object))不从object继承得来的类称为经典类(如class A()) 新式类跟经典类的差别主要是以下几点: 1 ...

  5. python中property属性的介绍及其应用

    Python的property属性的功能是:property属性内部进行一系列的逻辑计算,最终将计算结果返回. 使用property修饰的实例方法被调用时,可以把它当做实例属性一样 property的 ...

  6. python中的元类介绍

    类也是对象 在大多数编程语言中,类就是一组用来描述如何生成一个对象的代码段,在python中也是成立的. class ObjectCreator: pass my_object = ObjectCre ...

  7. Python中的lambda函数介绍

    Lambda函数,即Lambda 表达式(lambda expression),是一个匿名函数(不存在函数名的函数),Lambda表达式基于数学中的λ演算得名,直接对应于其中的lambda抽象(lam ...

  8. Python中set的功能介绍

    Set的功能介绍 1.集合的两种函数(方法) 1. 集合的内置函数 交集 格式:x.__and__(y)等同于x&y 例如:s1 = {'a',1,} s2 = {'b',1,} s3 = { ...

  9. Python中dict的功能介绍

    Dict的功能介绍 1. 字典的两种函数(方法) 1. 字典的内置函数 包含关系 格式:x.__contains__(key)等同于key in x 例如:dic = {'ab':23,'cd':34 ...

随机推荐

  1. 说说流控制(RTS/CTS/DTR/DSR 你都明白了吗?)【转】

    转自:http://bbs.ednchina.com/BLOG_ARTICLE_129041.HTM 以前写的博文,转过来 ============== 先引用一篇网文,作者不详,因几个地方都说自己是 ...

  2. ansible报错Using a SSH password instead of a key is not possible because Host Key checking is enabled and sshpass does not support this

    安装和配置好ansible,执行命令时报错如下 [root@test01 ansible-install]# ansible test -m shell -a 'w' >> Using a ...

  3. 一个有趣的小例子,带你入门协程模块-asyncio

    一个有趣的小例子,带你入门协程模块-asyncio 上篇文章写了关于yield from的用法,简单的了解异步模式,[https://www.cnblogs.com/c-x-a/p/10106031. ...

  4. java多线程快速入门(十三)

    死锁产生的原因(必须有两个线程.必须有多个锁.锁之间必须有引用的过程) package com.cppdy; class MyThread9 implements Runnable { private ...

  5. tomcat 输入学习

    Tomcat学习—Tomcat7 修改/webapps/ROOT发布路径(Linux和windows环境) https://blog.csdn.net/u010648555/article/detai ...

  6. hdu5358 推公式+在一个区间内的尺取+枚举法

    尺取+枚举,推出公式以后就是一个枚举加尺取 但是这题的尺取不是对一个值尺取,而是在一个区间内,所以固定左边界,尺取右边界即可 #include<bits/stdc++.h> #define ...

  7. bootstrap 文本对齐风格

    Bootstrap通过定义四个类名来控制文本的对齐风格: ☑   .text-left:左对齐 ☑   .text-center:居中对齐 ☑   .text-right:右对齐 ☑   .text- ...

  8. .NetCore源码阅读笔记系列之HttpAbstractions(五) Authentication

    说道认证&授权其实这块才是核心,这款跟前面Security这块有者紧密的联系,当然 HttpAbstractions 不光是认证.授权.还包含其他Http服务和中间价 接下来先就认证这块结合前 ...

  9. Spring事务传播行为

    什么是事务传播行为 public void methodA(){ methodB(); //doSomething } @Transaction(Propagation=XXX) public voi ...

  10. ubuntu ufw防火墙软件的配置入门

    顺便,一条龙作完安全吧. ufw的使用,是比iptables简单.但只能作简单的事儿,更改简单的netfilter里的iptable里的记录.难点的,可能还是得iptables原生命令. 自打2.4版 ...