1

When using Python and doing a Select statement to MYSQL to select 09 from a column the zero gets dropped and only the 9 gets printed.

Is there any way to pull all of the number i.e. including the leading zero?

Adam Chetnik
  • 1,906
  • 5
  • 27
  • 38
  • What is the data type of the column? Is it a text column (varchar) or a true numeric column (integer, decimal, ...)? If it is just a matter of how the value is printed, you could use Python's *%* operator, like *"%04d" % (value_of_column,)* – Dirk Aug 20 '09 at 18:40
  • he column type is tinyint. It gives me the leading zero when using PHP to Select from the table – Adam Chetnik Aug 20 '09 at 18:43

5 Answers5

4

There's almost certainly something in either your query, your table definition, or an ORM you're using that thinks the column is numeric and is converting the results to integers. You'll have to define the column as a string (everywhere!) if you want to preserve leading zeroes.

Edit: ZEROFILL on the server isn't going to cut it. Python treats integer columns as Python integers, and those don't have leading zeroes, period. You'll either have to change the column type to VARCHAR, use something like "%02d" % val in Python, or put a CAST(my_column AS VARCHAR) in the query.

Eevee
  • 47,412
  • 11
  • 95
  • 127
3

MySQL supports this in the column definition:

CREATE TABLE MyTable (
  i TINYINT(2) ZEROFILL
);

INSERT INTO MyTable (i) VALUES (9);

SELECT * FROM MyTable;

+------+
| i    |
+------+
|   09 | 
+------+
Bill Karwin
  • 538,548
  • 86
  • 673
  • 828
1

Best option will be using CAST as suggested by Eevee but you have to use CAST ( ur_field AS CHAR(2) ) as casting to varchar has this problem as given in this post

How to convert from varbinary to char/varchar in mysql

Community
  • 1
  • 1
abhilash
  • 245
  • 4
  • 10
0

What data type is the column? If you want to preserve leading zeros, you should probably use a non-numeric column type such as VARCHAR.

To format numbers with leading zeros in Python, use a format specifier:

>>> print "%02d" % (1,)
01
John Millikin
  • 197,344
  • 39
  • 212
  • 226
0

You could run each query on that column through a function such as:

if len(str(number)) == 1: number = "0" + str(number)

This would cast the number to a string but as far as I know, Python doesn't allow leading zeroes in its number datatypes. Someone correct me if I'm wrong.

Edit: John Millikin's answer does the same thing as this but is more efficient. Thanks for teaching me about format specifiers!

Travis
  • 12,001
  • 8
  • 39
  • 52