Inexplicably how to use python to connect to sql server for local testing

Background:
There is a project that wants to use python to connect to the sqlserver with the A ip address to fetch data, and then perform some operations on the tables inside to get the result table. The result table must be stored in the mysql server with the B ip address, because the A ip address The sqlserver server needs to log in to the government affairs cloud. After logging in, the Internet cannot be accessed. Therefore, it is decided to use the local sqlserver server for the connection test first, and then connect to the sql server with the A ip address after success.

Then, I started looking around, and it feels very strange that no one taught how to establish a local sql server connection? Or am I searching in the wrong way? In short, I checked around, and now I got connected by mistake.

Main steps
1. Follow Tencent's website tutorial (https://cloud.tencent.com/developer/article/1889410) to install sql server and Microsoft SQL Server Management Studio 18A, and remember the account number and password in this step .

After these two are installed, I looked at the server name and it feels strange. Now I want to connect to the local sql server in navicat. The insert image description here
information that navicat needs to fill in is as follows (I don’t know what the host writes, but my navicat is still Connected to the mysql of this machine, the host inside is also filled with localhost, so I tried localhost, and then filled in the username and password that I just set during the download process of Tencent Cloud, and the result!!! The connection is successful !!!)

insert image description here
insert image description here
The next step is to use Python's pyodbc to connect to the sql server hahahaha

insert image description here
If you add this sentence, you will not report an error. If you don’t add it, you will report the following error (refer to https://stackoverflow.com/questions/71732117/laravel-sql-server-error-odbc-driver-18-for-sql -serverssl-provider-error141 solved) insert image description here
Yay! ! ! ! The connection is successfulinsert image description here

code show as below:

import pyodbc
import pandas as pd
# Some other example server values are
# server = 'localhost\sqlexpress' # for a named instance
# server = 'myserver,port' # to specify an alternate port
server = 'localhost'
database = 'test'
username = 'sa'
password = 'XXXXXX' #自己的密码,这里我就不显示我自己的了
cnxn = pyodbc.connect('DRIVER={ODBC Driver 18 for SQL Server};SERVER='+server+';DATABASE='+database+';UID='+username+';PWD='+ password+';TrustServerCertificate=yes;')
cursor = cnxn.cursor()
sql = 'select * from zztest'
cursor.execute( sql )
columns = ['id']
data = cursor.fetchall()
data = pd.DataFrame(data, columns=columns)
print(data)

insert image description here

Guess you like

Origin blog.csdn.net/u012076669/article/details/126456529