1

I created a table with 100 records and now i want to generate a python function which takes a number and the table name and pulls records from the referenced table. ie. function should selects 'n' records from specified table.

I have already stated querying the database using python scripts. I can do a regular select but every time i want to select i have to edit the query. Is there a way for me to write a function in python that would take two parameters; eg.(n, table) that will allow me to select n records from any table in my database?

Is this possible and if it is where should i start?

summerdaiz
  • 77
  • 1
  • 9
  • Check this [answer](http://stackoverflow.com/a/622308/2932244) – JRodDynamite Oct 19 '15 at 06:44
  • Possible duplicate of [How do I connect to a MySQL Database in Python?](http://stackoverflow.com/questions/372885/how-do-i-connect-to-a-mysql-database-in-python) – ojii Oct 19 '15 at 06:45
  • Not sure if you sent the correct link. I already started writing to and querying the database using python scrips. I am able to do a select from but i need something dynamic/flexible and not hard coded. – summerdaiz Oct 19 '15 at 06:50
  • see additional comments @JRodDynamite – summerdaiz Oct 19 '15 at 06:57
  • not a duplicate of the link you sent @ojii please see additional comments for clarity. – summerdaiz Oct 19 '15 at 15:22

1 Answers1

2

You can use below function

def query_db( no_of_rows, table_name ):
  cur = db.cursor()
  query = """
    select top %d rows from %s
  """ %( int(no_of_rows), table_name )
  cur.execute(query)
  for row in cur.fetchall() :
    print row[0]

Is this what you want, or am i missing something?

Shrey
  • 1,242
  • 1
  • 13
  • 27
  • I had to tweek the query a little because im using MySQL. However the this error pops up when i try to call the function (name 'rooms' is not defined). The name of the table is rooms. I am trying to resolve it with assigning a table name to it statically. @Shrey – summerdaiz Oct 19 '15 at 13:58