I am trying to read SQL table in python. below script I was using and able to read data correctly.
Data = pd.read_sql_query("SELECT * from Data where [ID] = " + id ,engine)
But when in type for column ID changed to nvarchar, I got below error.
DatabaseError: Execution failed on sql 'SELECT * from Data where [ID] = 123': ('42000', '[42000] [Microsoft][ODBC SQL Server Driver][SQL Server]Error converting data type nvarchar to numeric. (8114) (SQLExecDirectW)')
Is there any way in which we can filter the table using a nvarchar column?
First of all, c. fetchall() retrieves ALL the results from your query, we'll put them in a variable called rows . Then we create a iterator (the thing you tried to do with the while loop) by doing for row in rows . Then we simply print each row.
I really need to emphasize that while this solution did solve the original question's problem, string concatenation used within SQL query text usually indicates a SQL injection vulnerability. Don't do this. Consider that most packages and libraries for SQL connections will offer a bona fide method for passing data into your query using placeholders along with parameters- use this. If you are determined to use string concatenation anyway- don't concatenate data from external sources/users/clients/anyone but 'you.' You have been warned.
If ID is a nvarchar, you need to be casting id
to be that as well.
Data = pd.read_sql_query("SELECT * from Data where [ID] = CAST(" + id + " AS NVARCHAR(10))", engine)
NOTE: I passed in a 10 for your NVARCHAR(size), but you'll ultimately have to determine what that should be.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With