python sql server database connected achieve CRUD python sql server database connected achieve CRUD

python sql server database connected achieve CRUD

  Brief

  python Microsoft sql server database connection with third-party modules, called pymssql (document: http: //www.pymssql.org/en/stable/index.html). Can be seen in official documents, pymssql is based _mssql module package to do is to comply with the interface specification DBAPI python relationship between the two as shown below:

  1. pymssql sql server database connected to the database and to achieve the basic operation (official api http://www.pymssql.org/en/stable/ref/pymssql.html)

1) The basic syntax

Copy the code
import pymssql 

server = "187.32.43.13" # connect to the server address
user = "root" # connection account
password = "1234" # connection password

conn = pymssql.connect (server, user, password, " connected to the default database name") # get the connection 
cursor = conn.cursor () # get the cursor

# Create a table 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) ) "" ")  

# Insert multiple rows of data cursor.executemany( "INSERT INTO persons VALUES (%d, %s, %s)", [(1, 'John Smith', 'John Doe'), (2, 'Jane Doe', 'Joe Dog'), (3, 'Mike T.', 'Sarah H.')]) # You must call commit () submitted to keep your data if you do not automatically submit to true conn.commit()
# Query data the cursor.execute ( 'the FROM persons the WHERE SalesRep the SELECT * =% S', 'John Doe')

# through the data (stored in the tuple) Embodiment 1 row = cursor.fetchone() while row: print("ID=%d, Name=%s" % (row[0], row[1])) row = cursor.fetchone()
# Through the data (stored in the tuple) mode 2 
for Row in Cursor:
Print ( 'R & lt Row =%'% (Row,))


# through the data (stored in the dictionary)
# 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()
# Close the connection
conn.Close () 

# Note: At any time, at the next connection, database operation is being performed only once a cursor object appears

Copy the code

2) At the same time, if you can use another grammar: with manual shut down to avoid cursors and connection connection

Copy the code
import pymssql 

server = "187.32.43.13" # connect to the server address
user = "root" # connection account
password = "1234" # connection password

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

3) call a stored procedure:

Copy the code
with pymssql.connect(server, user, password, "tempdb") 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']))
Copy the code

 

    2. Use_mssql连接sql server数据库并实现操作(官方api  http://www.pymssql.org/en/stable/ref/_mssql.html)

1) The basic syntax:

Copy the code
import _mssql
# Create a connection
conn = _mssql.connect(server='SQL01', user='user', password='password', \
    database='mydatabase')
print(conn.timeout)
print(conn.login_timeout) # Create a table conn.execute_non_query('CREATE TABLE persons(id INT, name VARCHAR(100))') # Insert data conn.execute_non_query("INSERT INTO persons VALUES(1, 'John Doe')") conn.execute_non_query("INSERT INTO persons VALUES(2, 'Jane Doe')") # Query operation conn.execute_query('SELECT * FROM persons WHERE salesrep=%s', 'John Doe') for row in conn: print "ID=%d, Name=%s" % (row['id'], row['name']) # Inquiry number count () numemployees = conn.execute_scalar("SELECT COUNT(*) FROM employees") # A query data employeedata = conn.execute_row("SELECT * FROM employees WHERE id=%d", 13) # Parameter query with a few examples: conn.execute_query('SELECT * FROM empl WHERE id=%d', 13) conn.execute_query('SELECT * FROM empl WHERE name=%s', 'John Doe') conn.execute_query('SELECT * FROM empl WHERE id IN (%s)', ((5, 6),)) conn.execute_query('SELECT * FROM empl WHERE name LIKE %s', 'J%') conn.execute_query('SELECT * FROM empl WHERE name=%(name)s AND city=%(city)s', \ { 'name': 'John Doe', 'city': 'Nowhere' } ) conn.execute_query('SELECT * FROM cust WHERE salesrep=%s AND id IN (%s)', \ ('John Doe', (1, 2, 3))) conn.execute_query('SELECT * FROM empl WHERE id IN (%s)', (tuple(xrange(4)),)) conn.execute_query('SELECT * FROM empl WHERE id IN (%s)', \ (tuple([3, 5, 7, 11]),)) # Close the connection conn.close()
Copy the code

 

pymssql hosted on Github: https: //github.com/pymssql

  Brief

  python Microsoft sql server database connection with third-party modules, called pymssql (document: http: //www.pymssql.org/en/stable/index.html). Can be seen in official documents, pymssql is based _mssql module package to do is to comply with the interface specification DBAPI python relationship between the two as shown below:

  1. pymssql sql server database connected to the database and to achieve the basic operation (official api http://www.pymssql.org/en/stable/ref/pymssql.html)

1) The basic syntax

Copy the code
import pymssql 

server = "187.32.43.13" # connect to the server address
user = "root" # connection account
password = "1234" # connection password

conn = pymssql.connect (server, user, password, " connected to the default database name") # get the connection 
cursor = conn.cursor () # get the cursor

# Create a table 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) ) "" ")  

# Insert multiple rows of data cursor.executemany( "INSERT INTO persons VALUES (%d, %s, %s)", [(1, 'John Smith', 'John Doe'), (2, 'Jane Doe', 'Joe Dog'), (3, 'Mike T.', 'Sarah H.')]) # You must call commit () submitted to keep your data if you do not automatically submit to true conn.commit()
# Query data the cursor.execute ( 'the FROM persons the WHERE SalesRep the SELECT * =% S', 'John Doe')

# through the data (stored in the tuple) Embodiment 1 row = cursor.fetchone() while row: print("ID=%d, Name=%s" % (row[0], row[1])) row = cursor.fetchone()
# Through the data (stored in the tuple) mode 2 
for Row in Cursor:
Print ( 'R & lt Row =%'% (Row,))


# through the data (stored in the dictionary)
# 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()
# Close the connection
conn.Close () 

# Note: At any time, at the next connection, database operation is being performed only once a cursor object appears

Copy the code

2) At the same time, if you can use another grammar: with manual shut down to avoid cursors and connection connection

Copy the code
import pymssql 

server = "187.32.43.13" # connect to the server address
user = "root" # connection account
password = "1234" # connection password

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

3) call a stored procedure:

Copy the code
with pymssql.connect(server, user, password, "tempdb") 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']))
Copy the code

 

    2. Use_mssql连接sql server数据库并实现操作(官方api  http://www.pymssql.org/en/stable/ref/_mssql.html)

1) The basic syntax:

Copy the code
import _mssql
# Create a connection
conn = _mssql.connect(server='SQL01', user='user', password='password', \
    database='mydatabase')
print(conn.timeout)
print(conn.login_timeout) # Create a table conn.execute_non_query('CREATE TABLE persons(id INT, name VARCHAR(100))') # Insert data conn.execute_non_query("INSERT INTO persons VALUES(1, 'John Doe')") conn.execute_non_query("INSERT INTO persons VALUES(2, 'Jane Doe')") # Query operation conn.execute_query('SELECT * FROM persons WHERE salesrep=%s', 'John Doe') for row in conn: print "ID=%d, Name=%s" % (row['id'], row['name']) # Inquiry number count () numemployees = conn.execute_scalar("SELECT COUNT(*) FROM employees") # A query data employeedata = conn.execute_row("SELECT * FROM employees WHERE id=%d", 13) # Parameter query with a few examples: conn.execute_query('SELECT * FROM empl WHERE id=%d', 13) conn.execute_query('SELECT * FROM empl WHERE name=%s', 'John Doe') conn.execute_query('SELECT * FROM empl WHERE id IN (%s)', ((5, 6),)) conn.execute_query('SELECT * FROM empl WHERE name LIKE %s', 'J%') conn.execute_query('SELECT * FROM empl WHERE name=%(name)s AND city=%(city)s', \ { 'name': 'John Doe', 'city': 'Nowhere' } ) conn.execute_query('SELECT * FROM cust WHERE salesrep=%s AND id IN (%s)', \ ('John Doe', (1, 2, 3))) conn.execute_query('SELECT * FROM empl WHERE id IN (%s)', (tuple(xrange(4)),)) conn.execute_query('SELECT * FROM empl WHERE id IN (%s)', \ (tuple([3, 5, 7, 11]),)) # Close the connection conn.close()
Copy the code

 

pymssql hosted on Github: https: //github.com/pymssql

Guess you like

Origin www.cnblogs.com/fyly/p/11074460.html