Use python to connect to SQL server database

Python uses the pymssql module to connect to the SQL server.

1. First install (pip install pymssql)

2. Create a connection object

  

  • useconnectCreate connection object
  • connect.cursorCreate a cursor object, the execution of SQL statements are basically carried out on the cursor
  • cursor.executeXXXMethod executes the SQL statement,cursor.fetchXXXGet query results, etc.
  • transfercloseMethod to close the cursorcursorConnect to the database

 

pymssql.connect(pymssql.connect(server='.',user='',password='',database='',timeout=0,login_timeout=60,charset ='UTF-8',as_dict=False,host='',appname=None,port ='1433',conn_properties,autocommit=False,tds_version='7.1' )

 

   The constructor used to create a connection to the database. Return oneConnectionObject.

  Connect parameter meaning:

parameter:
  • server(str)-Database host
  • user(str)-The database user connection is
  • password(str) - user password
  • database(str)-The database you are initially connected to
  • timeout(int)-The query timeout in seconds, the default is 0 (no timeout)
  • login_timeout(int)-Connection and login timeout in seconds, the default is 60
  • charset(str)-The character set used to connect to the database
  • conn_properties-The SQL query sent to the server when the connection is established. It can be a string or other type of string iteration. Default value: see_mssql.connect()
  • as_dict(Boolean)-Whether the row should be returned as a dictionary instead of a tuple
  • appname(str)-Set the name of the application used to connect
  • port(str)-TCP port used to connect to the server
  • autocommit(Boolean)-Whether to use the default automatic submission mode
  • tds_version(str)-The TDS protocol version to be used.

3. Properties of the connection object (connection object)

  

  Connection.autocommitstatus

among themstatusIs a Boolean value. This method turns on or off the automatic submission mode.

By default, the auto-commit mode is turned off, which means that if the changed data is to be saved in the database, each transaction must be explicitly committed.

You can turn on automatic submission mode, which means that every operation is submitted immediately once it succeeds.

The pymssql extension of DB-API 2.0.

  Connection.close

Close the connection.

  Connection.cursor

Return a cursor object, which can be used to query and retrieve results from the database.

  Connection.commit

Commit the current transaction. If you leave auto-commit as the default, you must call this method to save the dataFalse

4. Cusor object method (SQL statement call

Cursor.close

Close the cursor. From this point of view, the cursor is not available.

Cursor.execute(operation
Cursor.execute(operation,params

operation is a string, if specifiedparams, It is a simple value, a tuple, a dictionary orNone

Performing operations on the database may replace parameter placeholders with the provided values. This should be the preferred method of creating SQL commands, rather than manually concatenating strings, which is potentialReasons for SQL injection attacks. This method accepts the built-inString interpolation operatorSimilar format. However, since format and type conversion are handled internally, only%swith%dPlaceholder. Both placeholders are functionally equivalent.

If you provideparamsDictionaries support keyed placeholders.

if youexecute()Called with one parameter, the%The symbol loses its special meaning, so you can use it in the query string as usual, for example inLIKEOperator.

You must call firstConnection.commit()execute()Otherwise your data will not remain in the database. You can also setconnection.autocommitDo you want it to be done automatically. DB-API requires this behavior, if you don’t like it, please_mssqlUse the module instead.

Cursor.executemanyoperationparams_seq 

operation is an S sentence QL string,params_seqIs a series of data tuples. Repeat the database operation for each element in the parameter sequence.

E.g:

 

Cursor.fetchone

Return the query to a sentence, that is, a primitive (row).

Cursor.fetchmanysize = None 

Return query to size statement

Cursor.fetchall

Return all the ancestors in the query, as a list

Cursor.nextset

This method causes the cursor to jump to the next available result set, discarding all remaining rows in the current set.TrueIf the next result is available,NoneThe return value, if there is none.

Cursor.__iter__
Cursor.next

These methods helpPython iterator protocol. You will most likely not call them directly, but indirectly through the use of iterators.

The pymssql extension of DB-API 2.0.

Cursor.setinputsizes
Cursor.setoutputsize

These methods do nothing, as allowed by the DB-API specification.

 

Examples:

import pymssql

#Connect to local database
con = pymssql.connect(host = 'localhost',user = '',password = '',database = 'DB_STU')

 #Create cursor object
cur = con.cursor()

  

Intelligent Recommendation

Use Jmeter to connect to SQL Server database

Use Jmeter to connect to SQL Server database 1. The first step is to download the jar package 2. In the second step, Jmeter adds the jar package path 3. The third step is to add a thread group 4. The ...

python connect to database oracle, mysql, sql server

1. The library used by python to connect to oracle is cx_Oracle, We first install the cx_Oracle module, I mainly use pip install cx_Oracle, python version is 3.6. Note the following code: connect ('us...

Python Connect MySQL, SQL Server Database

First download the corresponding module win+R Open CMD, execute Then you can find Python's path in the environment variable, in ... (your Python path) \ python \ lib \ site-packages can find the above...

Python Connect to MySQL, SQL Server, Oracle Database

The first sentence is an example of the statement of MySQL connections. The second sentence is an example of statement, Host represents the server, user name, the password represents the password, and...

More Recommendation

Python - How to connect SQL Server Database

First, install a third party module First, you want to download the module named "pymsql", then IMPORT this module Installation method: 1. Press WIN + R ----> Enter cmd-> Enter the fol...

Connect to the sql server database

Connect to the sql server database In the scrapy pipeline test...

Sql Server connect to the database

Two commonly used methods to connect to the database: Before using the code to connect to the database, you need to introduce a namespace using System.Data; using System.Data.SqlClient; Use Sql Server...

Copyright  DMCA © 2018-2026 - All Rights Reserved - www.programmersought.com  User Notice

Top