【问题标题】:MySQL database updates to the round decimalMySQL 数据库更新到小数点后
【发布时间】:2015-05-21 21:08:31
【问题描述】:

我正在使用 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()

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

【问题讨论】:

    标签: python mysql decimal rounding mysql-python


    【解决方案1】:

    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 表,从一开始就包含一个具有 DECIMAL 数据类型的 number 字段,然后从一开始就将浮点数存储为小数。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-03-25
      • 1970-01-01
      • 2013-09-20
      • 1970-01-01
      • 2020-04-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多