gpt4 book ai didi

python - MySQL数据库更新到小数点

转载 作者:行者123 更新时间:2023-11-29 06:27:02 25 4
gpt4 key购买 nike

我正在使用 Python 2.7 和 MySQLdb。我正在尝试更新我设置为数据的小数并将其设置为数字,但我得到的是最接近的整数。这是代码:

Value = 5
data = 5
data = data + 0.5
print(data)
x.execute(""" UPDATE Testing SET number = %s WHERE id = %s """, (data, Value))
conn.commit()

例如,如果数据 = 5.5 并且我尝试更新数据库,我在表中看到数字是 6,而我希望它是 5.5。我见过其他一些人问过同样的问题,但不是在 Python 中。数字是一个 INT。请你帮助我好吗?提前致谢。

最佳答案

Testing 数据库表中的number 列显然具有整数数据类型。您可以通过查询 EXPLAIN Testing 来检查数据类型。如果它具有整数数据类型,则 number 值在存储到表中之前会被强制转换为整数。

如果你想存储小数,那么你需要先修改表格:

ALTER TABLE `Testing` CHANGE `number` `number` DECIMAL(M,D)

其中(根据 the docs ):

  • M 是最大位数(精度)。它的范围是 1 到 65。

  • D 是小数点右边的位数(刻度)。它范围为 0 到 30,并且不得大于 M


例如,如果我们创建一个 Testing 表,其中 number 的数据类型为 INT(11):

import MySQLdb
import config

def show_table(cursor):
select = 'SELECT * FROM Testing'
cursor.execute(select)
for row in cursor:
print(row)

def create_table(cursor):
sql = 'DROP TABLE Testing'
cursor.execute(sql)
sql = '''CREATE TABLE `Testing` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`number` INT(11),
PRIMARY KEY (id))'''
cursor.execute(sql)

with MySQLdb.connect(host=config.HOST, user=config.USER,
passwd=config.PASS, db='test') as cursor:

create_table(cursor)

假设表中有一条number = 5的记录:

    insert = 'INSERT INTO Testing (number) VALUE (%s)'
cursor.execute(insert, (5,))
show_table(cursor)
# (1L, 5L)

如果我们尝试将 number 设置为 5.5:

    update = 'UPDATE Testing SET number = %s where id = %s'
cursor.execute(update, [5.5, 1])

相反,数字存储为 6:

    show_table(cursor)
# (1L, 6L)

如果我们将 number 字段的数据类型更改为 DECIMAL(8,2):

    alter = 'ALTER TABLE `Testing` CHANGE `number` `number` DECIMAL(8,2)'
cursor.execute(alter)

然后将数字设置为 5.5 将 number 存储为小数:

    cursor.execute(update, [5.5, 1])
show_table(cursor)
# (1L, Decimal('5.50'))

当然,您也可以创建一个 Testing 表,其中的 number 字段从一开始就是 DECIMAL 数据类型,然后 float 将从开始。

附言。如果您真的想要 DECIMAL(M,D) 数据类型,(对我而言)还不是很清楚。如果您使用 DECIMAL(M,D),则查询该表将返回 number,在 Python 端是 decimal.Decimal。如果您只想要常规的 Python float ,则使用数据类型为 FLOAT 而不是 DECIMAL(M,D) 的 number 字段定义 Testing )

关于python - MySQL数据库更新到小数点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30384351/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com