SoFunction
Updated on 2024-10-29

Teach you how to connect to sql server with python

First install the pymssql library using pip

pip install pymssql

Specific connections, test code:

# server defaults to 127.0.0.1, if you open the TCP dynamic port you need to add the port number, such as '127.0.0.1:1433'.
# user defaults to sa
# password is the password you set for yourself
# database is the name of the database
server = '127.0.0.1'
user = "sa"
password = "123456"
database = "pubs"
conn = (server, user, password, database)
# can be simplified to conn = (host='localhost', user='sa', password='123456', database='pubs')
cursor = ()
('SELECT * FROM titles')
print( () ) 

# If you read the database with pandas
import pymssql
import pandas as pd
conn = ('IP address','Account Number','Password','Database')
sql_1 = "SELECT Id,create_time from table name"
#Use pandas to get data directly"
data = pd.read_sql(sql_1, conn)
()
print(data)

Encapsulated version:

#coding=utf-8 
# sqlserver connection
import pymssql

class MSSQL:
    def __init__(self,host,user,pwd,db):
         = host
         = user
         = pwd
         = db

    def __GetConnect(self):
        """
        Get connection information
        come (or go) back: ()
        """
        if not :
            raise(NameError,"No database information set")
         = (host=,user=,password=,database=,charset="utf8")
        cur = ()
        if not cur:
            raise(NameError,"Failed to connect to database.")
        else:
            return cur

    def ExecQuery(self,sql):
        """
        Execute the query statement
        What is returned is a list containing tuples, where the elements of the list are the rows of records and the elements of the tuples are the fields for each row of records

        """
        cur = self.__GetConnect()
        (sql)
        resList = ()

        #Must close the connection after the query is complete
        ()
        return resList

    def ExecNonQuery(self,sql):
        """
        Executing Non-Query Statements

        Recall Example:
            cur = self.__GetConnect()
            (sql)
            ()
            ()
        """
        cur = self.__GetConnect()
        (sql)
        ()
        ()

def main():
	# host is 127.0.0.1 by default, if you open the TCP dynamic port you need to add the port number, such as '127.0.0.1:1433'.
    # user defaults to sa
    # pwd is the password you set for yourself
    # db is the database name
    ms = MSSQL(host='127.0.0.1',user="sa",pwd="123456",db="pubs")
    resList = ("SELECT * FROM titles")
    print(resList)

if __name__ == '__main__':
    main()

In the event of: (20009, b'DB-Lib error message 20009, severity 9:\nUnable to connect: Adaptive Server is unavailable or does not exist (SZS\SQLEXPRESS)\n')bailout-like,There are several possible reasons for this:

1. Wrong database name

/ip protocol is not enabled, this is located (right click on this computer, click on management, click on services and applications, click on sql configuration manager, click on sql server network configuration, click on protocols for mssqlserver, right click on tcp/ip, click on enable, restart the computer to take effect)

image-20210513190459194

3. dynamic port error, the default is not open dynamic port, if you open the need to write the port number, in the 2 tcp/ip protocol to view the dynamic port number, click on the tcp/ip protocol, click on the ip address, and then turn over to the bottom, find ipall Inside the dynamic port number, you can also delete the dynamic port number, and then do not write the

image-20210513190632988

User login not enabled

Open sql server management studio, click security, click login name, if the sa item appears red x then it means sa user login is not enabled, right click sa click properties, click status to enable.

image-20210515232825986

image-20210515232720453

to this article on how to teach you how to use python to connect sql server article is introduced to this, more related python to connect sql server content please search for my previous articles or continue to browse the following related articles I hope that you will support me more in the future!