Python MySQLConnector模块
MySQL Connector/Python 是 MySQL 官方提供的 Python 连接 MySQL 数据库的驱动程序.下载地址为: http://www.mysql.com/downloads/connector/python/,其为mysql官方推出的一个python数据库模块,相较于MySQLdb模块来说,其支持python3,而MySQLdb目前只支持到python2.7版本。这里就结合示例,总结下MySQL Connector模块的用法。
1、数据库连接
连接数据库的代码如下
1import mysql.connector
2config={'host':'127.0.0.1',#默认127.0.0.1
3 'user':'root',
4 'password':'123456',
5 'port':3306 ,#默认即为3306
6 'database':'test',
7 'charset':'utf8'#默认即为utf8
8 }
9try:
10 cnn=mysql.connector.connect(**config)
11except mysql.connector.Error as e:
12 print('connect fails!{}'.format(e))
连接方法上和MySQLdb模块略有不同。MySQLdb使用的是=号,这里使用的是 : 号。
2、创建表
下面我们根据上面新建的一个数据库连接创建一张名为student的表:
1sql_create_table='CREATE TABLE `student`
2(`id` int(10) NOT NULL AUTO_INCREMENT,
3`name` varchar(10) DEFAULT NULL,
4`age` int(3) DEFAULT NULL,
5PRIMARY KEY (`id`))
6ENGINE=MyISAM DEFAULT CHARSET=utf8'
7cursor=cnn.cursor()
8try:
9 cursor.execute(sql_create_table)
10except mysql.connector.Error as e:
11 print('create table orange fails!{}'.format(e))
3、插入数据
插入数据的语法上和MySQLdb上基本上是一样的:
1cursor=cnn.cursor()
2try:
3 '第一种:直接字符串插入方式'
4 sql_insert1="insert into student (name, age) values ('orange', 20)"
5 cursor.execute(sql_insert1)
6 '第二种:元组连接插入方式'
7 sql_insert2="insert into student (name, age) values (%s, %s)"
8 #此处的%s为占位符,而不是格式化字符串,所以age用%s
9 data=('shiki',25)
10 cursor.execute(sql_insert2,data)
11 '第三种:字典连接插入方式'
12 sql_insert3="insert into student (name, age) values (%(name)s, %(age)s)"
13 data={'name':'mumu','age':30}
14 cursor.execute(sql_insert3,data)
15 #如果数据库引擎为Innodb,执行完成后需执行cnn.commit()进行事务提交
16except mysql.connector.Error as e:
17 print('insert datas error!{}'.format(e))
18finally:
19 cursor.close()
20 cnn.close()
同样,MySQL Connector也支持多次插入,同样其使用的也是cursor.executemany,示例如下:
1stmt='insert into student (name, age) values (%s,%s)'
2data=[
3 ('Lucy',21),
4 ('Tom',22),
5 ('Lily',21)]
6cursor.executemany(stmt,data)
4、查询操作
1cursor=cnn.cursor()
2try:
3 sql_query='select id,name from student where age > %s'
4 cursor.execute(sql_query,(21,))
5 for id,name in cursor:
6 print ('%s's age is older than 25,and her/his id is %d'%(name,id))
7except mysql.connector.Error as e:
8 print('query error!{}'.format(e))
9finally:
10 cursor.close()
11 cnn.close()
5、删除操作
1cursor=cnn.cursor()
2try:
3 sql_delete='delete from student where name = %(name)s and age < %(age)s'
4 data={'name':'orange','age':24}
5 cursor.execute(sql_delete,data)
6except mysql.connector.Error as e:
7 print('delete error!{}'.format(e))
8finally:
9 cursor.close()
10 cnn.close()
捐赠本站(Donate)
如您感觉文章有用,可扫码捐赠本站!(If the article useful, you can scan the QR code to donate))
- Author: shisekong
- Link: https://blog.361way.com/python-mysql-connector/3850.html
- License: This work is under a 知识共享署名-非商业性使用-禁止演绎 4.0 国际许可协议. Kindly fulfill the requirements of the aforementioned License when adapting or creating a derivative of this work.