473,394 Members | 2,100 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,394 software developers and data experts.

MS Access db (mdb): viewing table attributes

I have an Access 2003 database, protected by a workgroup, that I am
trying to view through python. Currently, I'm attempting dao with the
win32 package, and I'm able to view all of the table names, but I don't
know how to view the attributes of the tables.

My code:

import win32com.client
from pprint import pprint

#sample code to list all tables in the selected database
daoEngine = win32com.client.Dispatch('DAO.DBEngine.36')
dtbs = daoEngine.OpenDatabase('database_file.mdb')
for table in dtbs.TableDefs:
if table.Name[:4] <> "MSys" and table.Name[:4] <> "~TMP":
pprint(table.Name.encode('utf-8'))
#the above works, but below does not:
for col in table.Fields:
pprint(col.Name, Col.Type, Col.Size)

I am getting that len(Fields) = 0, and I know the database tables are
all full of columns (and data). Is there also some resource that
defines all the properties of TableDefs? I wasn't able to find a
python reference for this.

Thank You,
Gau

Mar 10 '06 #1
13 6211
Em Sex, 2006-03-10 Ã*s 09:53 -0800, ga*****@gmail.com escreveu:
I have an Access 2003 database, protected by a workgroup, that I am
trying to view through python. Currently, I'm attempting dao with the
win32 package, and I'm able to view all of the table names, but I don't
know how to view the attributes of the tables.


I don't know if you can't use ODBC, but that's what I'm using now to
access an Access database. A (maybe) useful snippet:

import dbi, odbc # The order of this import is important!
connection = odbc.odbc('Driver={Microsoft Access Driver (*.mdb)};' +
'Dbq=C:\database.mdb;Uid=Admin;Pwd=;')
cursor = connection.cursor()
cursor.execute('SELECT column1, column2, COUNT(*) FROM table' +
'WHERE column1 < column2' +
'GROUP BY column1, column2')
print cursor.fetchall()

AFAIK, the main advantage is that it is easier to change to another
database later if needed, as the odbc module uses the same interface as
many others.

At least in my application, it has the same performance as Access itself
(most of my queries return just some sums and groups, none of them
return big chunks of data, so most part of the processing is kept on the
Jet side).

Hope that helps,
Felipe.

--
"Quem excele em empregar a força militar subjulga os exércitos dos
outros povos sem travar batalha, toma cidades fortificadas dos outros
povos sem as atacar e destrói os estados dos outros povos sem lutas
prolongadas. Deve lutar sob o Céu com o propósito primordial da
'preservação'. Desse modo suas armas não se embotarão, e os ganhos
poderão ser preservados. Essa é a estratégia para planejar ofensivas."

-- Sun Tzu, em "A arte da guerra"

Mar 10 '06 #2
Here is the full code I'm using now to try out your sample:

import dbi, odbc
import win32com.client
from pprint import pprint

#sample code to list all tables in the selected database
daoEngine = win32com.client.Dispatch('DAO.DBEngine.36')
dtbs = daoEngine.OpenDatabase('database.mdb')
for table in dtbs.TableDefs:
if table.Name[:4] <> "MSys" and table.Name[:4] <> "~TMP":
pprint(table.Name.encode('utf-8'))

#sample code that will execute a stored query with parameters
dbconn = odbc.odbc('DSN=db; UID=user; PWD=pass')
dbcursor = dbconn.cursor()
dbcursor.execute('execute "result specs" 1')
dbcursor.execute('SELECT column1, column2, COUNT(*) FROM Weight ' +
'WHERE column1 < column2 ' +
'GROUP BY column1, column2')
#pprint(dbcursor.fetchall())
dbcursor.close()
dbconn.close()

I get the error: dbcursor.execute('SELECT column1, column2, COUNT(*)
FROM Weight ' +
dbi.program-error: [Microsoft][ODBC Microsoft Access Driver] Too few
parameters. Expected 2. in EXEC

Mar 10 '06 #3
ok, I know what I had wrong :) I was hoping that your code would
return the column names for me, but it was expecting me to list the
columns to use. I want to know how to retrieve that list of columns
through python.

Mar 10 '06 #4
Gau,

I'm a beginner and had fits connecting to my Access 2003 DB of
quotations. The best advice that finally worked for me was to use
mxODBC. In fact, you might just search this forum for Access and
mxODBC.

I can't customize to fit your situation, but here is the connection
part of a script I use to extract a random quote. I'm on Windows XP
using newest Python from ActiveState.

# Based on
# http://aspn.activestate.com/ASPN/Coo.../Recipe/389535
# Instructions for customizing are at:
# http://www.egenix.com/files/python/mxODBC.html

import mx.ODBC.Windows as odbc
import random
import textwrap

driv='DRIVER={Microsoft Access Driver (*.mdb)};DBQ=d:/Access
Databases/Quotations2005'

conn = odbc.DriverConnect(driv)
c = conn.cursor()

# Just counts the quotes, doesn't select them
c.execute ("SELECT COUNT(Quote) FROM Table1")

# Yields the number of rows with something in the quote field
total_quotes = c.fetchone()

# Get a random number somewhere between
# 1 and the number of total quotes

quote_number = random.randint(1, total_quotes[0])

# Select a quote where the ID matches that number
c.execute ("SELECT Author, Quote FROM QUOTES7 WHERE ID = %d" %
quote_number)

quote = c.fetchone()

The rest of the script just deals with formatting and presentation of
the quote.

Hope this helps.

rpd

Mar 10 '06 #5
>> I was hoping that your code would
return the column names for me, but it was expecting me to list the
columns to use. I want to know how to retrieve that list of columns
through python.


I think once you establish connection to the database using Python and
mxODBC, then your question becomes an SQL question not a Python
question.

rpd

Mar 10 '06 #6
That would be fine for me to switch to mxodbc, I've used it before and
it worked fine. But if I switch, do you know how I can get the column
names from the table? Maybe I'm not being clear with my question here.
I'm going to try again....

here's a table (it's in access):

=== tablename = mytable ===

id | user | pass | access privileges <-- these are the
column names I want
================================
0 bob 12345 admin/full
1 sam 53432 power user
4 mike 43234 guest

I know how to connect to the database.
I know how to get the table names.
How can I get the names of the columns for each table??

Mar 10 '06 #7
BartlebyScrivener:

Maybe you're right, and I'll try posting to another group. However, I
have found resources for doing this using the same data structure:
"TableDefs" which is in VB and python. I see how they are doing it in
VB, but I don't know how this works in python. I was hoping someone
could at least point me to the details of this object, so I could then
examine it's properties myself. In VB, it looks like it's more of a
property of the object and not an SQL query.

Mar 10 '06 #8
For more reference, I got my information to start this from:
http://aspn.activestate.com/ASPN/Coo...n/Recipe/52267

When I try to run that code, it gives me this:
File "C:\Python24\Lib\site-packages\win32com\client\util.py", line
83, in next
return _get_good_object_(self._iter_.next())
pywintypes.com_error: (-2146825178, 'OLE error 0x800a0c26', None, None)

The error is pointing to:
"for idx in currTabl.Indexes:"

Mar 10 '06 #9
>> How can I get the names of the columns for each table??

SELECT * FROM mytable

Mar 10 '06 #10
ga*****@gmail.com wrote:
I have an Access 2003 database, protected by a workgroup, that I am
trying to view through python. Currently, I'm attempting dao with the
win32 package, and I'm able to view all of the table names, but I don't
know how to view the attributes of the tables.

My code:

import win32com.client
from pprint import pprint

#sample code to list all tables in the selected database
daoEngine = win32com.client.Dispatch('DAO.DBEngine.36')
dtbs = daoEngine.OpenDatabase('database_file.mdb')
for table in dtbs.TableDefs:
if table.Name[:4] <> "MSys" and table.Name[:4] <> "~TMP":
pprint(table.Name.encode('utf-8'))
#the above works, but below does not:
for col in table.Fields:
pprint(col.Name, Col.Type, Col.Size)

I am getting that len(Fields) = 0, and I know the database tables are
all full of columns (and data). Is there also some resource that
defines all the properties of TableDefs? I wasn't able to find a
python reference for this.

Thank You,
Gau

Not quite sure about DAO but when I use ODBC I get the fieldnames
by doing (stripped from working program):

crsr.execute(SQL_query)
fieldinfo=crsr.description
fieldnames=["%s" % i[0].lower() for i in fieldinfo]

Hope this helps.

-Larry Bates

Mar 10 '06 #11
Gau,

This prints the names of the columns in my database.

# Modification of
# http://aspn.activestate.com/ASPN/Coo.../Recipe/389535
# Instructions for customizing are at:
# http://www.egenix.com/files/python/mxODBC.html

import mx.ODBC.Windows as odbc

driv='DRIVER={Microsoft Access Driver (*.mdb)};DBQ=d:/Access
Databases/Quotations2005'

conn = odbc.DriverConnect(driv)
c = conn.cursor()

# get the column names from Table1
c.execute ("SELECT * FROM Table1")

# get column names
cols= [ i[0] for i in c.description ]
print '\n\ncols=',cols

Mar 10 '06 #12
BartlebyScrivener wrote:
Gau,

This prints the names of the columns in my database.

# Modification of
# http://aspn.activestate.com/ASPN/Coo.../Recipe/389535
# Instructions for customizing are at:
# http://www.egenix.com/files/python/mxODBC.html

import mx.ODBC.Windows as odbc

driv='DRIVER={Microsoft Access Driver (*.mdb)};DBQ=d:/Access
Databases/Quotations2005'

conn = odbc.DriverConnect(driv)
c = conn.cursor()

# get the column names from Table1
c.execute ("SELECT * FROM Table1")

# get column names
cols= [ i[0] for i in c.description ]
print '\n\ncols=',cols

Note that there's no requirement that the SELECT actually retrieve any
data, son the normal technique is to use a query guaranteed to return no
rows, such as

SELECT * FROM Table1 WHERE 1=0

See also

http://aspn.activestate.com/ASPN/Coo...n/Recipe/81189

for an algorithm that will show data fron an arbitrary query in a
reasonably tidy display.

regards
Steve
--
Steve Holden +44 150 684 7255 +1 800 494 3119
Holden Web LLC/Ltd www.holdenweb.com
Love me, love my blog holdenweb.blogspot.com

Mar 11 '06 #13
Thanks so much for the information, both of you. I guess I should have
just looked at it more simply to begin with. Now, I can move on to
more complicated information retrieval :-) My ultimate plan with this
task is to get whatever table attributes I can, like foreign/primary
keys, data types & length/size, etc. You both have been a great help.

Mar 12 '06 #14

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

7
by: Mark Lees | last post by:
How does one increase their Access skills? I'm creating a basic DB for a non-profit organization. I would classify myself as an advanced beginner. I've got some help books but it seems they...
28
by: Neil Ginsberg | last post by:
I have a client who is using Access 2002/2000 (the database itself is written in 2000), and is considering migrating to Access 2003. Any recommendations on whether Access 2003 is worth the migrate,...
6
by: Larry R Harrison Jr | last post by:
I have Access XP, and the following code which is supposed to assign a JPEG to an image control: Me.Image9.Picture = "F:\Pictures\CP775_SonyDSCP50\FingerRockNight_Resize.jpg" I get this error...
3
by: Scott Simonson | last post by:
Hello, I am fighting a losing battle with Access's Image control. At one time it was able to load TIF images that my users were viewing. I had written two totally different Access apps. Basically...
1
by: Harry Devine | last post by:
I have a DataGrid that is configured to use the Edit/Update/Cancel concept correctly. My grid shows values from 5 database fields. I only need to update that last 4 fields. The last field is a...
2
by: John R. Dougherty | last post by:
I am using VB.NET, and have experience coding to open an Access .MDB file for retrieving/updating data. But I would like to be able to get at the schema of the database - see the tables list, list...
6
by: news.microsoft.com | last post by:
Hope someone can help Working Visual Web Developer 2005 using Access databases It all works fine using the WebDevelopers webserver but when I use IIS I get these errors The Microsoft Jet...
1
by: gm | last post by:
Hi; I have written a database that tracks all the installation we have ever done. I have a small heating company. I have recently started keeping a directory of digital photographs of the...
10
by: mukeshhtrivedi | last post by:
Hi, I have some MDB (MS Access 2000) files on our server. It is small application created by one of our employee long time ago. I see this application is on Network Drive G: and H: (both drive has...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.