Python Forum
How to print database column types?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How to print database column types?
#1
I've started to experiment with python database and have the simple demo below working.

BUT, I'm concerned about the date column in the table... it seems to print OK but is the data "type" really a date type?

I ask because I read here http://www.cs.toronto.edu/~nn/csc309/gui...nsFIN.html

that the sql date data type format should be yyyy-mm-dd
BUT, if you notice in the code I inadvertently entered the date as month/day/year...

SO, the question is did the date go in the record as a date or as a string or what?

How do I have Python print out the data type for each column in a table?

This is important later when you attempt to sort by or search for a date or whatever.

Thanks for any help.



import sqlite3
connection = sqlite3.connect('demo.db')
cursor = connection.cursor()
cursor.execute ("CREATE TABLE tableA(id integer primary key not null, Name varchar2(25), Date date, notes varchar2(200))")
connection.commit()
cursor.execute ("INSERT INTO tableA values(1,'Elvis','8/29/17','bla bla bla')")
cursor.execute ("INSERT INTO tableA values(2,'Sting','8/31/17','do da do da day')")
connection.commit()
cursor.execute ("SELECT * FROM tableA")
while True:
        row = cursor.fetchone()
        if row == None:
            break
        print (row[0],row[1],row[2])
Reply
#2
Most databases are smart enough to know what a date looks like in various local areas.  For most of the USA, for example, dates are frequently mm/dd/yy (a lot of Europe is dd/mm/yyyy, as well as US military), so most databases accept that as input.  It'll still be formatted as yyyy-mm-dd when you select the data back out of it, though.

Furthermore, the data type for the column is "date".  If you tried to insert something that the database didn't recognize as a real date, it'd throw an error and nothing would be inserted.
Reply
#3
What is the database management system?
In postgresSQL, you would use:
 select column_name, data_type from information_schema.columns where where table_name = 'tablename';
Other systems should have something similar.
Reply
#4
It looks like sqlite, which means you might be able to use the much simpler describe table_name;
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  How to Randomly Print a Quote From a Text File When User Types a Command on Main Menu BillKochman 13 898 Apr-24-2024, 05:47 AM
Last Post: Bronjer
  Database that can compress a column, or all data, automatically? Calab 3 1,194 May-22-2023, 03:25 AM
Last Post: Calab
  How to print the 2nd column of a searched string in a csv ptey07 2 2,042 Jan-11-2020, 11:25 AM
Last Post: ptey07
  list comprehension : print column as row pyseeker 4 3,669 Sep-05-2019, 05:40 AM
Last Post: pyseeker

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020