Washington Muniz
Washington Muniz

Reputation: 100

Importing a .sql file in python

I have just started learning SQL and I'm having some difficulties to import my sql file in python.

The .sql file is in my desktop, as well is my .py file.

That's what I tried so far:

import codecs
from codecs import open
import pandas as pd
sqlfile = "countries.sql"
sql = open(sqlfile, mode='r', encoding='utf-8-sig').read()
pd.read_sql_query("SELECT name FROM countries")

But I got the following message error:

TypeError: read_sql_query() missing 1 required positional argument: 'con'

I think I have to create some kind of connection, but I can't find a way to do that. Converting my data to an ordinary pandas DataFrame would help me a lot.

Thank you

Upvotes: 1

Views: 14343

Answers (2)

masat
masat

Reputation: 350

You need a database connection. I don't know what SQL flavor are you using, but suppose you want to run your query in SQL server

import pyodbc
con = pyodbc.connect(driver='{SQL Server}', server='yourserverurl', database='yourdb', trusted_connection=yes)

then pass the connection instance to pandas

pd.read_sql_query("SELECT name FROM countries", con)

more about pyodbc here

And if you want to query an SQLite database

import sqlite3
con = sqlite3.connect('pathto/example.db')

More about sqlite here

Upvotes: 1

mrEvgenX
mrEvgenX

Reputation: 766

This is the code snippet taken from https://www.dataquest.io/blog/python-pandas-databases/ should help.

import pandas as pd
import sqlite3
conn = sqlite3.connect("flights.db")
df = pd.read_sql_query("select * from airlines limit 5;", conn)

Do not read database as an ordinary file. It has specific binary format and special client should be used.

With it you can create connection which will be able to handle SQL queries. And can be passed to read_sql_query.

Refer to documentation often https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_sql_query.html

Upvotes: 1

Related Questions