MySQL 数据库更新到小数位数

MySQL database updates to the round decimal

我正在使用 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 并且我尝试更新数据库,我在 table 中看到数字是 6,而我希望它是 5.5。我看到其他一些人问过同样的问题,但 Python 中没有。数字是一个 INT。请你帮助我好吗?提前致谢。

Testing 数据库 table 中的 number 列显然具有整数数据类型。您可以通过查询EXPLAIN Testing来检查数据类型。如果它具有整数数据类型,则 number 值在存储到 table.

之前被强制转换为整数

如果你想存储小数,那么你需要先改变table:

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

其中(根据 the docs):

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

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


例如,如果我们创建 Testing table 且 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)

假设 table 有一条记录 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 table,其中 number 字段从一开始就具有 DECIMAL 数据类型,然后浮点数将从开始。

PS。如果您真的想要 DECIMAL(M,D) 数据类型,(对我而言)还不是很清楚。如果您使用 DECIMAL(M,D),那么查询 table 将 return number 是 Python 一侧的 decimal.Decimal。如果您只想要常规 Python 浮点数,则使用数据类型为 FLOAT 而不是 DECIMAL(M,D).

number 字段定义 Testing