Connector for Python
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了Connector for Python,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2847字,纯文字阅读大概需要5分钟。
内容图文
![Connector for Python](/upload/InfoBanner/zyjiaocheng/834/517a32ca845642a0bf0ec2a8fee11149.jpg)
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() |
内容总结
以上是互联网集市为您收集整理的Connector for Python全部内容,希望文章能够帮你解决Connector for Python所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。