sql-server connection python django

1. Preparations

python3.6 connections necessary to introduce pymssql sqlserver database module

pymssql official: https://pypi.org/project/pymssql/

There is no need to install it:

pip install:

pip install pymssql

 

2. Connect database

First you have to define the target database: 'server name', "account name", "password", "database name"

Because these parameters are necessary

Here use the local database for testing:

Here is the link statement:

Copy the code
import pymssql # introduced pymssql module


def conn():
    connect = pymssql.connect ( '(local)', 'sa', '**********', 'test') # server name, account, password, database name
    if connect:
        print ( "connection success!")
    return connect


if __name__ == '__main__':
    conn = conn()
Copy the code

 

operation result:

connection succeeded!

Process finished with exit code 0

 

3. CRUD (CRUD)

    Create a new database table:

Copy the code
import pymssql

connect = pymssql.connect ( '(local)', 'sa', 'password1633', 'test') # establish a connection
if connect:
    print ( "connection success!")
    
cursor = connect.cursor () # create a cursor object, python in the sql statement must be performed by a cursor
cursor.execute("create table C_test02(id varchar(20))")   #执行sql语句
connect.commit()  #提交
cursor.close()   #关闭游标
connect.close()  #关闭连接
Copy the code

 

注意当执行更改数据库表的操作时,执行完sql后别忘记加一句commit().

close()是必须的,否则python程序会一至占用这个数据库.

增加(Create):

Copy the code
import pymssql

connect = pymssql.connect('(local)', 'sa', 'password1633', 'test')  #建立连接
if connect:
    print("连接成功!")
    
cursor = connect.cursor()   #创建一个游标对象,python里的sql语句都要通过cursor来执行
sql = "insert into C_test (id, name, sex)values(1002, '张si', '女')"
cursor.execute(sql)   #执行sql语句
connect.commit()  #提交
cursor.close()   
connect.close()  
Copy the code

 

运行结果:

 

查询(Retrieve):

Copy the code
import pymssql

connect = pymssql.connect('(local)', 'sa', 'password1633', 'test')  #建立连接
if connect:
    print("连接成功!")
    
cursor = connect.cursor()   #创建一个游标对象,python里的sql语句都要通过cursor来执行
sql = "select name, sex from C_test"
cursor.execute(sql)   #执行sql语句
row = cursor.fetchone()  #读取查询结果,
while row:              #循环读取所有结果
    print("Name=%s, Sex=%s" % (row[0],row[1]))   #输出结果
    row = cursor.fetchone()

cursor.close()   
connect.close()
Copy the code

 

运行结果:

Update (Update) and delete (Delete) operations are similar. Rewritten sql statement on the line.

 

 

 

With use of a cursor and stored procedures

 

Pymssql database connections manner and using substantially the same sqlite:

 

  • Use connectcreate a connection object
  • connect.cursorCreate a cursor object, execute SQL statements basically carried out on the cursor
  • cursor.executeXXXMethod executes SQL statements, cursor.fetchXXXget the query results, etc.
  • Call the closemethod Closes the cursor cursorand database connections

 

import pymssql

# server 数据库服务器名称或IP # user 用户名 # password 密码 # database 数据库名称 conn = pymssql.connect(server, user, password, database) cursor = conn.cursor() # 新建、插入操作 cursor.execute(""" IF OBJECT_ID('persons', 'U') IS NOT NULL DROP TABLE persons CREATE TABLE persons ( id INT NOT NULL, name VARCHAR(100), salesrep VARCHAR(100), PRIMARY KEY(id) ) """) cursor.executemany( "INSERT INTO persons VALUES (%d, %s, %s)", [(1, 'John Smith', 'John Doe'), (2, 'Jane Doe', 'Joe Dog'), (3, 'Mike T.', 'Sarah H.')]) # 如果没有指定autocommit属性为True的话就需要调用commit()方法 conn.commit() # 查询操作 cursor.execute('SELECT * FROM persons WHERE salesrep=%s', 'John Doe') row = cursor.fetchone() while row: print("ID=%d, Name=%s" % (row[0], row[1])) row = cursor.fetchone() # 也可以使用for循环来迭代查询结果 # for row in cursor: # print("ID=%d, Name=%s" % (row[0], row[1])) # 关闭连接 conn.close()

 

Note: Examples of parameters used in a query operation %sinstead '%s', if the parameter value is a string, it will automatically single quotes when executing the statement

 

Note the use of the cursor

 

A connection only one cursor query is active, as follows:

 

c1 = conn.cursor()
c1.execute('SELECT * FROM persons') c2 = conn.cursor() c2.execute('SELECT * FROM persons WHERE salesrep=%s', 'John Doe') print( "all persons" ) print( c1.fetchall() ) # 显示出的是c2游标查询出来的结果 print( "John Doe" ) print( c2.fetchall() ) # 不会有任何结果

 

To avoid this problem you can use the following two ways:

 

  • Create multiple connections to ensure that multiple queries can be executed in parallel on different connection cursor
  • Use fetchalllower again after the execution method to get the cursor to the results of a query, as follows:

 

c1.execute('SELECT ...') c1_list = c1.fetchall() c2.execute('SELECT ...') c2_list = c2.fetchall()

 

Cursor behavior dictionary variable return

 

Each row of the query results obtained above example, the cursor tuple type,
can specify when you create a cursor as_dictto the cursor variable parameter returns the dictionary,
the dictionary key is the data table column names

 

conn = pymssql.connect(server, user, password, database)
cursor = conn.cursor(as_dict=True)

cursor.execute('SELECT * FROM persons WHERE salesrep=%s', 'John Doe') for row in cursor: print("ID=%d, Name=%s" % (row['id'], row['name'])) conn.close()

 

Use withstatement (context manager)

 

By using withstatement to display the call omitted closeclose the connection method and cursors

 

with pymssql.connect(server, user, password, database) as conn: with conn.cursor(as_dict=True) as cursor: cursor.execute('SELECT * FROM persons WHERE salesrep=%s', 'John Doe') for row in cursor: print("ID=%d, Name=%s" % (row['id'], row['name']))

 

Call a stored procedure

 

above 2.0.0 version pymssql can cursor.callprocto call a stored procedure method

 

with pymssql.connect(server, user, password, database) as conn: with conn.cursor(as_dict=True) as cursor: # 创建存储过程 cursor.execute(""" CREATE PROCEDURE FindPerson @name VARCHAR(100) AS BEGIN SELECT * FROM persons WHERE name = @name END """) # 调用存储过程 cursor.callproc('FindPerson', ('Jane Doe',)) for row in cursor: print("ID=%d, Name=%s" % (row['id'], row['name']))

 

Guess you like

Origin www.cnblogs.com/baili-luoyun/p/11094011.html