0% acharam este documento útil (0 voto)
125 visualizações8 páginas

Como Conectar o Python Ao SQL Server Usando Pyodbc - Data To Fish

O documento explica como conectar o Python ao SQL Server usando o pacote pyodbc no Python. Ele descreve as etapas para instalar o pyodbc, obter o nome do servidor, banco de dados e tabela, e conectar o Python ao SQL Server usando um exemplo simples.

Enviado por

Anderson Muniz
Direitos autorais
© © All Rights Reserved
Levamos muito a sério os direitos de conteúdo. Se você suspeita que este conteúdo é seu, reivindique-o aqui.
Formatos disponíveis
Baixe no formato PDF, TXT ou leia on-line no Scribd
0% acharam este documento útil (0 voto)
125 visualizações8 páginas

Como Conectar o Python Ao SQL Server Usando Pyodbc - Data To Fish

O documento explica como conectar o Python ao SQL Server usando o pacote pyodbc no Python. Ele descreve as etapas para instalar o pyodbc, obter o nome do servidor, banco de dados e tabela, e conectar o Python ao SQL Server usando um exemplo simples.

Enviado por

Anderson Muniz
Direitos autorais
© © All Rights Reserved
Levamos muito a sério os direitos de conteúdo. Se você suspeita que este conteúdo é seu, reivindique-o aqui.
Formatos disponíveis
Baixe no formato PDF, TXT ou leia on-line no Scribd
Você está na página 1/ 8

7/25/2020 Como conectar o Python ao SQL Server usando pyodbc - Data to Fish

Dados para Pescar


Casa » Pitão » Como conectar o Python ao SQL Server usando pyodbc

Como conectar o Python ao SQL Server usando


pyodbc
Python / 26 de maio de 2020

Precisa conectar o Python ao SQL Server usando pyodbc?

Nesse caso, mostrarei as etapas para estabelecer esse tipo de conexão usando um exemplo
simples.

O exemplo a ser usado


Para começar, vamos revisar um exemplo em que:

O nome do servidor é: RON \ SQLEXPRESS


O nome do banco de dados é: TestDB
O nome da tabela (com um esquema dbo) é: dbo.Person
A tabela dbo.Person contém os seguintes dados:

Nome Era Cidade

Jade 20 Londres

Maria 119 Nova Iorque

Martin 25 Londres

Roubar 35 Genebra

Maria 42. Paris

Jon 28. Toronto

https://datatofish.com/how-to-connect-python-to-sql-server-using-pyodbc/ 1/8
7/25/2020 Como conectar o Python ao SQL Server usando pyodbc - Data to Fish

Etapas para conectar o Python ao SQL Server usando


pyodbc
Etapa 1: instalar pyodbc

First, you’ll need to install the pyodbc package which will be used to connect Python to SQL
Server.

You can use the PIP install method to install the pyodbc package:

Step 2: Retrieve the server name

Now retrieve your server name.

In my case, the server name is: RON\SQLEXPRESS

https://datatofish.com/how-to-connect-python-to-sql-server-using-pyodbc/ 2/8
7/25/2020 Como conectar o Python ao SQL Server usando pyodbc - Data to Fish

One way to find your current server name is by running the following query:

SELECT @@SERVERNAME

Step 3: Obtain the database name

Next, obtain the database name in which your desired table is stored.

You can find the database name under the Object Explorer menu (underneath the Databases
section), which is located on the left side of your SQL Server.

In our example, the database name is: TestDB

Step 4: Get the table name

Now you’ll need to get the name of your desired table.

The name of your table would also be located under the Object Explorer menu (underneath the
Tables section).

Here, the name of the table is: dbo.Person

https://datatofish.com/how-to-connect-python-to-sql-server-using-pyodbc/ 3/8
7/25/2020 Como conectar o Python ao SQL Server usando pyodbc - Data to Fish

The following data will be displayed in SQL Server when you run a simple SELECT query using
the dbo.Person table. This is also the data that you’ll get once you connect Python to SQL
Server using pyodbc.

Step 5: Connect Python to SQL Server

And for the final part, open your Python IDLE and fill the server name, database and table
information.

Here is the structure of the code that you may use in Python:

import pyodbc
conn = pyodbc.connect('Driver={SQL Server};'

https://datatofish.com/how-to-connect-python-to-sql-server-using-pyodbc/ 4/8
7/25/2020 Como conectar o Python ao SQL Server usando pyodbc - Data to Fish

'Server=server_name;'
'Database=database_name;'
'Trusted_Connection=yes;')

cursor = conn.cursor()
cursor.execute('SELECT * FROM database_name.table')

for row in cursor:


print(row)

And this is how the code would look like in Python for our example:

Run the code in Python (adjusted to your server name, database and table information).

You’ll notice that the results that were printed in Python match with the info that was displayed in
SQL Server:

From SQL to Pandas DataFrame

https://datatofish.com/how-to-connect-python-to-sql-server-using-pyodbc/ 5/8
7/25/2020 Como conectar o Python ao SQL Server usando pyodbc - Data to Fish

You can take things further by going from SQL to Pandas DataFrame using pd.read_sql_query:

import pandas as pd
import pyodbc
conn = pyodbc.connect('Driver={SQL Server};'
'Server=RON\SQLEXPRESS;'
'Database=TestDB;'
'Trusted_Connection=yes;')

cursor = conn.cursor()

sql_query = pd.read_sql_query('SELECT * FROM TestDB.dbo.Person',conn)


print(sql_query)
print(type(sql_query))

When applying pd.read_sql_query, don’t forget to place the connection string variable at the
end. In our case, the connection string variable is conn.

Once you run the code (adjusted to your database connection information), you’ll get the
following Pandas DataFrame:

Note that the syntax of print(type(sql_query)) was also added to the code to confirm that now
we’ve got a DataFrame.

https://datatofish.com/how-to-connect-python-to-sql-server-using-pyodbc/ 6/8
7/25/2020 Como conectar o Python ao SQL Server usando pyodbc - Data to Fish

Conclusion and Additional Resources


Você viu como conectar o Python ao SQL Server. Depois de estabelecer uma conexão entre o
Python e o SQL Server, você pode começar a usar o SQL no Python para gerenciar seus
dados.

Você também pode usar o Python para inserir valores na tabela do SQL Server .

Se você quiser saber mais sobre os diferentes tipos de conexões entre o Python e outros
aplicativos de banco de dados, verifique os seguintes tutoriais:

Conecte o Python a um banco de dados Oracle usando cx_Oracle


Conecte o Python ao banco de dados MS Access usando pyodbc
Conecte o Python ao MySQL usando o MySQLdb

Para mais informações sobre o pacote pyodbc , visite a documentação do pyodbc .

← Post anterior Próximo Post →

Tutoriais

Tutoriais em Python

R Tutorials

Julia Tutorials

Tutoriais de scripts em lote

Tutoriais do MS Access

Tutoriais do Excel

Direitos autorais © 2020 | Dados para Pescar

https://datatofish.com/how-to-connect-python-to-sql-server-using-pyodbc/ 7/8
7/25/2020 Como conectar o Python ao SQL Server usando pyodbc - Data to Fish

Política de Privacidade

Termos de serviço

Todos os direitos reservados ©

https://datatofish.com/how-to-connect-python-to-sql-server-using-pyodbc/ 8/8

Você também pode gostar