python操作mysql数据库第三方库_python与数据库连接的代码

python操作mysql数据库第三方库_python与数据库连接的代码MySQL系列–4.使用Python3访问数据库

大家好,又见面了,我是你们的朋友全栈君。

MySQL系列–4.使用Python3访问数据
1、安装MySQL驱动
pip install mysql-connector
安装完成后进入命令行模式,导入驱动,如果不报错,说明安装成功

Python 3.6.7 (default, Oct 22 2018, 11:32:17)
[GCC 8.2.0] on linux
Type “help”, “copyright”, “credits” or “license” for more information.

import mysql.connector

2、安装MySQL

MySQL安装请参考:https://www.cnblogs.com/webDepOfQWS/p/10685617.html

3、操作数据库
MySQL操作数据库的一般步骤如下:
a、建立连接
b、通过连接对象得到游标对象
c、执行SQL语句,获取执行结果,如果执行的SQL语句会改变数据库或表 ,需要提交,才会保存修改。
d、关闭游标对象,关闭连接对象。

创建表并插入数据
在rms数据库中创建一张表:user_info并插入2条数据,创建表SQL语句如下:

create table user_info(

id int(10) primary key,
name char(20) not null,
passwd char(40) not null,
email char(20) not null,
phone char(20) not null,
role  char(10) not null,
sex char(10) not null,
status int(10) not null,
createAt datetime not null,
exprAt datetime not null,
validDays int(10) not null,
delAt datetime 

)ENGINE=InnoDB DEFAULT CHARSET=utf8;
Python3代码:

coding:utf-8

导入驱动

import mysql.connector

建立连接

conn = mysql.connector.connect(host=”127.0.0.1″,user=’root’,database=’rms’,password=’password’)

获游标标对象

cursor = conn.cursor()

SQL语句

SQL1=”’create table user_info(

id int(10) primary key,
name char(20) not null,
passwd char(40) not null,
email char(20) not null,
phone char(20) not null,
role  char(10) not null,
sex char(10) not null,
status int(10) not null,
createAt datetime not null,
exprAt datetime not null,
validDays int(10) not null,
delAt datetime 

)ENGINE=InnoDB DEFAULT CHARSET=utf8;”’
SQL2=”’insert into user_info values
(1,”StephenWang7″,”123456″,”123@qq.com”,”15103887470″,”admin”,”male”,”200″,”20190412201130″,”20190419201130″,30,null)”’
try:

#执行创建表的SQL语句
cursor.execute(SQL1)
#执行插入语句
cursor.execute(SQL2)
#提交
conn.commit()

except Exception as e:

print(e)

finally:

#关闭游标对象
cursor.close()
#关闭连接
conn.close

连接数据库查看结果:

mysql> select count(*) from user_info;
count(*)
2

1 row in set (0.27 sec)

mysql>
查询SQL执行结果
fetchone():返回一条结果。
fetchall():返回所有结果。
fetchmany([size]):返回size条结果。
示例1:

try:

cursor.execute("select  count(*) from user_info;")
#获取执行结果
result = cursor.fetchone()
print(result)

except Exception as e:

print(e)

输出1:

返回的是一个tuple

(2,)
示例2:
查询user_info表中所有的记录。

try:

cursor.execute("select  count(*) from user_info;")
#获取执行结果,fatchone 只返回一条结果
result = cursor.fetchone()
print(result)

except Exception as e:

print(e)

运行示例2的代码时,报错:Unread result found,在连接数据库时设置’buffered’: True。

conn = mysql.connector.connect(host=”127.0.0.1″,user=’root’,database=’rms’,password=’password’,buffered=True)
输出2:

(1, ‘StephenWang7’, ‘123456’, ‘123@qq.com’, ‘15103887470’, ‘admin’, ‘male’, 200, datetime.datetime(2019, 4, 12, 20, 11, 30), datetime.datetime(2019, 4, 19, 20, 11, 30), 30, None)
更新和删除
更新和删除的代码与创建表类似,需要说明的一点是执行语句之后需要提交(commmit)。

coding:utf-8

导入驱动

import mysql.connector

建立连接

conn = mysql.connector.connect(host=”127.0.0.1″,user=’root’,database=’rms’,password=’password’,buffered=True)

获游标标对象

cursor = conn.cursor()
try:

#执行更新语句
cursor.execute("update user_info  set passwd=%s where id=%s",['py123456',1])
#获取执行结果
result = cursor.fetchone()
print(result)
#提交
conn.commit()

except Exception as e:

print(e)

finally:

#关闭游标对象
cursor.close()
#关闭连接
conn.close

MySQL的占位符为%s,连接数据库查看结果:

mysql> select passwd from user_info where id=1;
passwd
py123456

1 row in set (0.03 sec)
原文地址https://www.cnblogs.com/webDepOfQWS/p/10693105.html

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/106880.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • js实现时钟代码

    js实现时钟代码代码<!DOCTYPEhtml><html><headlang=”en”><metacharset=”UTF-8″><title></title><style>/*全局*/*{margin:0;…

    2022年6月28日
    23
  • 面向对象进阶

    面向对象相关内置函数isinstance判断一个对象是否是一个类中的对象issubclass判断一个类是否是类中的子类返回布尔值反射反射的概念所谓的反射其实就是用字符串类型的名字去操作

    2022年3月29日
    37
  • c语言游戏小型程序代码,C语言小游戏源码「建议收藏」

    c语言游戏小型程序代码,C语言小游戏源码「建议收藏」在此提供C语言小游戏源码,包括扫雷游戏,贪吃蛇游戏,时钟等。运行时只要把红色部分改为自己电脑上TC目录的BGI分目录即可。//扫雷游戏#include#include#include#defineLEFTPRESS0xff01#defineLEFTCLICK0xff10#defineLEFTDRAG0xff19#defineMOUSEMOVE0xff08struct{int…

    2022年5月19日
    51
  • 进销存管理系统【源码开放】[通俗易懂]

    进销存管理系统【源码开放】[通俗易懂]进销存管理系统的功能需求:1,实现采购订单的持久化,对采购商品入库处理,还有就是采购的退货处理;2,实现商品的入库、出库操作,查询商品的库存信息,修改商品的仓库号3,实现销售订单的添加,销售发货处理,并且销售的退货处理4,实现新建员工培训信息和查询员工培训记录功能5,实现对商品、供应商、客户资料的管理,对员工用户的管理,最重要的是对系统数据的备份和恢复代码的截图如下所示:系统的截图如下所示:bean层manage的代码如下所示:packag.

    2022年5月31日
    27
  • nslookup命令解析域名_nslookup是什么意思

    nslookup命令解析域名_nslookup是什么意思1、作用:查询DNS的记录,查看域名解析是否正常,在网络故障的时候用来诊断网络问题。2、命令解析命令格式:nslookupdomain[dns-server]示例:nslookupwww.163.com第一部分服务器:本机DNS服务器信息。192.168.3.1是我当前计算机的DNS服务器,由于是内网服务器名称无法获取第二部分非权威应答:Non-authoritativeanswer,除非实际存储DNSServer中获得域名解析回答的,都称为非权威应答。也就.

    2022年10月19日
    0
  • 树莓派3B+使用GPIO实现串口通信[通俗易懂]

    树莓派3B+使用GPIO实现串口通信[通俗易懂]https://www.circuits.dk/setup-raspberry-pi-3-gpio-uart/

    2022年6月25日
    49

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号