Python Forum
add database rows to dataframe
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
add database rows to dataframe
#1
I'm trying to build a dataframe from rows I select incrementally from a database.

SQL = '''select ..... where userid = ? and roleName = ?"" I use the UserId and Role Name from the file in my where clause.
for index, row in data.iterrows():
        userid, rolename = row[['User Id', 'Role Name']]
        sql_query = pd.read_sql_query((SQL, (userid, rolename)), conn) <- This does not seem to be correct
        sqldf = pd.Dataframe(sql_query, columns = ['ApplicationName', 'Environment', 'LastName', 'FirstName', 'UniqueIdentifier', 'RoleName', 'UserId', 'AccountType'])
        conn.close()
        
return
Reply
#2
You write: "This does not seem to be correct". How can you tell? Does it generate an error message? In that case: show us the exact error message.
Reply
#3
This is the error
"pandas.io.sql.DatabaseEror: Execution failed on sql"

What I need to accomplish is loop through the data in a csv file.
take two of the columns and use them in my sql statement, then execute the sql.
Using SQL Server, pyodbc
This requires an new database connection for each row in the file, unless there is a way to do it all with one connection.
then I need to return each result to a new csv file.

Any advice will be greatly appreciated.
Reply
#4
I am sure Python gives you more information about the error than "pandas.io.sql.DatabaseEror: Execution failed on sql". It will tell you the exact line number in each module. I guess it will go wrong in "pd.read_sql_query()".
Best way is to add debug lines in your program to test whether variables contain what you expect.
First: somewhere in your program you must have logged in to the SQL Server database. Did that succeed? Can you test that with a simple query?
Second: just before executing the query: add statements to print the contents of the variables that matter.
        userid, rolename = row[['User Id', 'Role Name']]
        print("userid   = " + userid)
        print("rolename = " + rolename)
        Print("SQL      = " + SQL)
        sql_query = pd.read_sql_query((SQL, (userid, rolename)), conn)
What does it show?
Third: try to simplify the SQL. Do it without the variable substitution by SQL Server.
SQL = "select * from table_name where userid = 'John' and roleName = 'administrator'"
...
    sql_query = pd.read_sql_query(SQL, conn)
(First fill in the correct table_name, userid and rolename.) What is the result of that?
Reply
#5
If I hard code the userid and rolename it works,
but I need to do it with variables in the sql statment.

sql_query = pd.read_sql_query((SQL, [b](userid, rolename)[/b]), conn)
but the userid, rolename in bold does not seem to be the right syntax.
Reply
#6
I have also tried this syntax and it does not work either. gives a syntax error at the =.

sql_query = pd.read_sql_query((SQL, conn, params = (userid, rolename)))
Reply
#7
I am not aquainted with SQL Server and neither with pandas. But are you sure you are using the right syntax? Should it not be:
pd.read_sql_query(SQL, conn, params=(userid, rolename))
And when everything fails you can always change the SQL string:
...
userid, rolename = row[['User Id', 'Role Name']]
SQL = f"select * from tablename where userid = '{userid}' and roleName = '{rolename}'"
sql_query = pd.read_sql_query(SQL, conn)
...
And don't forget, if anything happens you don't understand: insert print statements to see what the program really does.

Just saw your message. I think you have too many brackets ().
And post the error message if you have one. Don't take it personal but people seem to not realize the error is not just some text, it is designed to tell you exact why python cannot execute what you coded.
Note there is a button to post error messages.
Reply
#8
The f-string is not working because it does not like some of the keywords from the sql statement.


Error:
Unexpected token AS RequestType,
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Rows not adding to sqlite3 database using SQLAlchemy Calab 11 1,656 Jun-02-2023, 05:53 PM
Last Post: bowlofred
  Converting a json file to a dataframe with rows and columns eyavuz21 13 4,406 Jan-29-2023, 03:59 PM
Last Post: eyavuz21
  How to assign a value to pandas dataframe column rows based on a condition klllmmm 0 828 Sep-08-2022, 06:32 AM
Last Post: klllmmm
  The code I have written removes the desired number of rows, but wrong rows Jdesi1983 0 1,630 Dec-08-2021, 04:42 AM
Last Post: Jdesi1983
  Partial Matching Rows In Pandas DataFrame Query eddywinch82 1 2,365 Jul-08-2021, 06:32 PM
Last Post: eddywinch82
  Pandas DataFrame combine rows by column value, where Date Rows are NULL rhat398 0 2,111 May-04-2021, 10:51 PM
Last Post: rhat398
  Indexing [::-1] to Reverse ALL 2D Array Rows, ALL 3D, 4D Array Columns & Rows Python Jeremy7 8 7,104 Mar-02-2021, 01:54 AM
Last Post: Jeremy7
Question Dataframe Manipulation Coping Rows and Removing Dates ashleysnl 1 1,775 Feb-26-2021, 10:00 PM
Last Post: nilamo
  How to split dataframe object rows to columns Mekala 1 2,496 Nov-12-2020, 04:18 PM
Last Post: michael1789
  Adding loop results as rows in dataframe Shreya10o 2 2,188 May-09-2020, 11:00 AM
Last Post: Shreya10o

Forum Jump:

User Panel Messages

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