Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Stepping through a MySQL table

Status
Not open for further replies.

Loomis

Programmer
Jan 4, 2000
30
US
I am new to Python, coming from Foxpro and C#. I have 300,000 names in a MySQL table sorted alphabetically by last name then first name. I need to be able to find a name and then scroll up or down to view similar names. I am using Python and MySQL. In Foxpro, I would execute a SEEK command to place the record pointer on the name I wanted, then I would move the pointer up or down to find similar names. From what I am reading, python uses a cursor to accomplish this functionality along with an SQL query. Am I on the right track? Is there a better approach?

thank you
 
Yes, you are on the right track.

Python does not have a SEEK command -- you can achieve similar through SQL queries that allow you to search for specific records and then retrieve surrounding records...
Basic outline:
  1. Connect to MySQL: First, establish a connection to your MySQL database using a library like mysql-connector-python or PyMySQL.
  2. Search for a Specific Name: To find a specific name, execute a query that locates the first instance of that name.
  3. Scroll Up or Down: After finding the specific name, write additional queries to retrieve a certain number of records before or after the current record. This would simulate scrolling up or down.
  4. Close the Connection: Close the cursor and connection when done.

Python:
import mysql.connector

def connect_to_db():
    # Establish connection to MySQL
    conn = mysql.connector.connect(
        host="localhost",
        user="yourusername",
        password="yourpassword",
        database="yourdatabase"
    )
    return conn

def find_name(cursor, last_name, first_name):
    # Find the specific name
    query = """
    SELECT * FROM names
    WHERE last_name = %s AND first_name = %s
    LIMIT 1;
    """
    cursor.execute(query, (last_name, first_name))
    result = cursor.fetchone()
    return result

def scroll_up(cursor, last_name, first_name, limit=10):
    # Scroll up to find previous records
    query_up = """
    SELECT * FROM names
    WHERE (last_name, first_name) < (%s, %s)
    ORDER BY last_name DESC, first_name DESC
    LIMIT %s;
    """
    cursor.execute(query_up, (last_name, first_name, limit))
    previous_records = cursor.fetchall()
    return previous_records

def scroll_down(cursor, last_name, first_name, limit=10):
    # Scroll down to find next records
    query_down = """
    SELECT * FROM names
    WHERE (last_name, first_name) > (%s, %s)
    ORDER BY last_name ASC, first_name ASC
    LIMIT %s;
    """
    cursor.execute(query_down, (last_name, first_name, limit))
    next_records = cursor.fetchall()
    return next_records

def main():
    # Connect to the database
    conn = connect_to_db()
    cursor = conn.cursor()

    # Define the name you want to search for
    last_name = "Smith"
    first_name = "John"

    # Find the specific name
    found_record = find_name(cursor, last_name, first_name)
    if found_record:
        print("Found Record:", found_record)

        # Scroll up to get previous records
        previous_records = scroll_up(cursor, last_name, first_name)
        print("\nPrevious Records:")
        for record in previous_records:
            print(record)

        # Scroll down to get next records
        next_records = scroll_down(cursor, last_name, first_name)
        print("\nNext Records:")
        for record in next_records:
            print(record)
    else:
        print("Name not found.")

    # Close the cursor and connection
    cursor.close()
    conn.close()

if __name__ == "__main__":
    main()

How to Run the Script​

Install MySQL Connector: Make sure you have the MySQL connector installed. If not, you can install it using pip:

Code:
pip install mysql-connector-python

Configure the Connection: Replace "localhost", "yourusername", "yourpassword", and "yourdatabase" with your actual MySQL server details.
Run the Script: Save the script as scroll_names.py and run it from the command line or your Python IDE:

Python:
python scroll_names.py
 
Yes, you are on the right track.

Python does not have a SEEK command -- you can achieve similar through SQL queries that allow you to search for specific records and then retrieve surrounding records...
Basic outline:
  1. Connect to MySQL: First, establish a connection to your MySQL database using a library like mysql-connector-python or PyMySQL.
  2. Search for a Specific Name: To find a specific name, execute a query that locates the first instance of that name.
  3. Scroll Up or Down: After finding the specific name, write additional queries to retrieve a certain number of records before or after the current record. This would simulate scrolling up or down.
  4. Close the Connection: Close the cursor and connection when done.

Python:
import mysql.connector

def connect_to_db():
    # Establish connection to MySQL
    conn = mysql.connector.connect(
        host="localhost",
        user="yourusername",
        password="yourpassword",
        database="yourdatabase"
    )
    return conn

def find_name(cursor, last_name, first_name):
    # Find the specific name
    query = """
    SELECT * FROM names
    WHERE last_name = %s AND first_name = %s
    LIMIT 1;
    """
    cursor.execute(query, (last_name, first_name))
    result = cursor.fetchone()
    return result

def scroll_up(cursor, last_name, first_name, limit=10):
    # Scroll up to find previous records
    query_up = """
    SELECT * FROM names
    WHERE (last_name, first_name) < (%s, %s)
    ORDER BY last_name DESC, first_name DESC
    LIMIT %s;
    """
    cursor.execute(query_up, (last_name, first_name, limit))
    previous_records = cursor.fetchall()
    return previous_records

def scroll_down(cursor, last_name, first_name, limit=10):
    # Scroll down to find next records
    query_down = """
    SELECT * FROM names
    WHERE (last_name, first_name) > (%s, %s)
    ORDER BY last_name ASC, first_name ASC
    LIMIT %s;
    """
    cursor.execute(query_down, (last_name, first_name, limit))
    next_records = cursor.fetchall()
    return next_records

def main():
    # Connect to the database
    conn = connect_to_db()
    cursor = conn.cursor()

    # Define the name you want to search for
    last_name = "Smith"
    first_name = "John"

    # Find the specific name
    found_record = find_name(cursor, last_name, first_name)
    if found_record:
        print("Found Record:", found_record)

        # Scroll up to get previous records
        previous_records = scroll_up(cursor, last_name, first_name)
        print("\nPrevious Records:")
        for record in previous_records:
            print(record)

        # Scroll down to get next records
        next_records = scroll_down(cursor, last_name, first_name)
        print("\nNext Records:")
        for record in next_records:
            print(record)
    else:
        print("Name not found.")

    # Close the cursor and connection
    cursor.close()
    conn.close()

if __name__ == "__main__":
    main()

How to Run the Script​

Install MySQL Connector: Make sure you have the MySQL connector installed. If not, you can install it using pip:

Code:
pip install mysql-connector-python

Configure the Connection: Replace "localhost", "yourusername", "yourpassword", and "yourdatabase" with your actual MySQL server details.
Run the Script: Save the script as scroll_names.py and run it from the command line or your Python IDE:

Python:
python scroll_names.py
Thank you for the thorough response.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top