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)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

发表回复

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

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