解决python查询数据库字段为decimal类型的数据结果为科学计数法的问题

410 阅读2分钟

解决python查询数据库字段为decimal类型的数据结果为科学计数法的问题#

Copy
select CAST(u.amount  AS CHAR) from user u

CAST(u.amount AS CHAR) ;u.amount: Decimal类型的字段#

这样查询出来的数据就不会是科学计数法了,但是查出来的数据类型就转成了字符串类型了#

验证#

准备数据库数据#

Copy
SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;

-- ----------------------------
-- Table structure for amount
-- ----------------------------
DROP TABLE IF EXISTS `amount`;
CREATE TABLE `amount`  (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
  `amount` decimal(65, 15) NOT NULL,
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;

-- ----------------------------
-- Records of amount
-- ----------------------------
INSERT INTO `amount` VALUES (1, 'desire', 14.025415550000000);
INSERT INTO `amount` VALUES (2, 'ronin', 0.253698741550000);
INSERT INTO `amount` VALUES (3, 'tom', 0.000000000000005);
INSERT INTO `amount` VALUES (4, 'aaa', 0.000000000000785);

SET FOREIGN_KEY_CHECKS = 1;

Python查询#

1、连接数据库,创建连接#

Copy
import pymysql

con = pymysql.connect(host='localhost',
                      user="root",
                      password="123456",
                      port=3306,
                      charset='utf8')
cur = con.cursor()

2、使用 * 查询所有的数据#

Copy
sql = "SELECT * FROM desire.amount a"
cur.execute(sql)
users = cur.fetchall()
print(users)

2.1、打印结果

Copy
((1, 'desire', Decimal('14.025415550000000')), (2, 'ronin', Decimal('0.253698741550000')), (3, 'tom', Decimal('5E-15')), (4, 'aaa', Decimal('7.85E-13')))

2.2 分析结果:从上面的打印结果可以看到,如果小数位过长,打印出来的数据就会变成科学计数法的形式打印,这样的数据看起来不是很清晰。

3、使用CAST() SQL函数,把Decimal类型的字段转成字符串显示#

Copy
sql = "SELECT a.id,a.name,CAST(a.amount  AS CHAR) FROM desire.amount a"
cur.execute(sql)
users = cur.fetchall()
print(users)

3.1 打印结果

Copy
((1, 'desire', '14.025415550000000'), (2, 'ronin', '0.253698741550000'), (3, 'tom', '0.000000000000005'), (4, 'aaa', '0.000000000000785'))

3.2 分析结果:这样打印出来的数据,就跟数据库存放的一致了,数据比对起来也是正确的,很清晰

4、经过这样处理,比对数据就显得稍微清晰一点,不会混杂着科学计数法的数据了。#

作者: DesireYang

出处:www.cnblogs.com/desireyang/…

版权:本文采用「署名-非商业性使用-相同方式共享 4.0 国际」知识共享许可协议进行许可。

Explicit is better than implicit(明了胜于晦涩)
希望对您有所帮助!感谢观看!
如要转载,请注明出处:转载自:www.cnblogs.com/desireyang/…