脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服务器之家 - 脚本之家 - Python - python 在mysql中插入null空值的操作

python 在mysql中插入null空值的操作

2021-09-16 00:06pirate945 Python

这篇文章主要介绍了python 在mysql中插入null空值的操作,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧

python在mysql中插入null空值

?
1
sql = “insert into mrodata (mmeues1apid) values (%s)”%‘null'

%s没有引号,可以将“null"中null写进数据库,达到null值效果。

%s加引号 values就是字符串,导致类型错误,插入错误。

?
1
sql = “insert into mrodata (mmeues1apid) values (‘%s')”%‘null'

补充:数据库中的空值与null的区别以及python中的nan和none

数据库里面的”空值”有两种:空字符(“”)、空值(null)。

两种存储方式在数据库中都很常见,实际中根据业务或者个人习惯可以用这两种方式来存储“空值”。

那这两种到底有什么区别,下面通过例子直接来展示:

?
1
2
3
4
5
6
7
8
9
10
11
-- 创建表test
create table `test` (
`id` int not null ,
`name` varchar(255) null ,
`date` timestamp null ,
`class` varchar(255) null
);
insert into test (id,name,date,class) values (1,'张三','2017-03-01','a班');
insert into test (id,name,date,class) values (2,'李四','2017-03-02','');
insert into test (id,name,class) values (3,'王五','c班');
select * from test;

python 在mysql中插入null空值的操作

?
1
select count(date),count(class) from test;

python 在mysql中插入null空值的操作

看到这里应该明白了,直观看空字符和null的区别在于,在做count计算的时候,空字符也会被计算在里面,而null不会。有些同学在使用where is null 和is not null 的时候也要注意数据库中的“空值”是空字符还是null。

不然统计结果可能并不是你想要的。

平时有些数据是需要借助python 来处理的,我们来看看python获取数据的时候有哪些需要注意的。

python有两种方式获取数据:

1. 一种是把数据从mysql 中导出到txt或者csv,然后本地读取;

2. 另一种是python直接链接数据库,读取数据;

先看第一种:导出到csv,python 读取

python 在mysql中插入null空值的操作

第二种:

python 在mysql中插入null空值的操作

两种方式读取的数据居然不一样!

1、第一种把数据从mysql导出后,python读取时,空值即为null;

2、第二种链接数据库后,python能读取表结构,数据库的null对应列表中的none以及pandas中的nan(如果字段类型是时间,则为nat)。而数据库中的空字符,则被识别为空字符。

个人理解的等式

null(数据库)=none(python列表)=nan(pandas)

空字符(数据库)=空字符(python列表)=空字符(pandas)

从csv中获取数据时:空值(csv)=null(数据库)=nan(pandas)

转为csv数据时:数据库中的null\空字符和pandas中的nan\空字符,都变成csv中的空值

在python处理完数据后,往数据库写数据的时候也一样。注意注意!

以上为个人经验,希望能给大家一个参考,也希望大家多多支持服务器之家。如有错误或未考虑完全的地方,望不吝赐教。

原文链接:https://blog.csdn.net/pirate945/article/details/88245886

延伸 · 阅读

精彩推荐