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?

5
  • Check this answer Commented Oct 19, 2015 at 6:44
  • Possible duplicate of How do I connect to a MySQL Database in Python? Commented Oct 19, 2015 at 6: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. Commented Oct 19, 2015 at 6:50
  • see additional comments @JRodDynamite Commented Oct 19, 2015 at 6:57
  • not a duplicate of the link you sent @ojii please see additional comments for clarity. Commented Oct 19, 2015 at 15:22

1 Answer 1

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?

Sign up to request clarification or add additional context in comments.

1 Comment

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.