解決python查詢數據庫字段為decimal類型的數據結果為科學計數法的問題
select CAST(u.amount AS CHAR) from user u
CAST(u.amount AS CHAR) ;u.amount: Decimal類型的字段
這樣查詢出來的數據就不會是科學計數法了,但是查出來的數據類型就轉成了字符串類型了
驗證
准備數據庫數據
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、連接數據庫,創建連接
import pymysql
con = pymysql.connect(host='localhost',
user="root",
password="123456",
port=3306,
charset='utf8')
cur = con.cursor()
2、使用 * 查詢所有的數據
sql = "SELECT * FROM desire.amount a"
cur.execute(sql)
users = cur.fetchall()
print(users)
2.1、打印結果
((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類型的字段轉成字符串顯示
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 打印結果
((1, 'desire', '14.025415550000000'), (2, 'ronin', '0.253698741550000'), (3, 'tom', '0.000000000000005'), (4, 'aaa', '0.000000000000785'))
3.2 分析結果:這樣打印出來的數據,就跟數據庫存放的一致了,數據比對起來也是正確的,很清晰
