Read MS-SQL database using python

Use python to read data in MS-SQL, the template pymssql is used here.

Because it is not a template that comes with python, you first need to use pip to install, the corresponding command: pip install pymssql

Create the main.py file and enter the code as follows:

1  import pymssql,os
 2  
3 server= " 127.0.0.1 "   #Server IP or server name 
4 user= " sa "            #The account used to log in to the database 
5 password= " password "  #The account password 
6 conn=pymssql.connect(server, user,password,database= ' master ' )
 7 cursor= conn.cursor()
 8 cursor.execute( " select name from sys.databases " ) #Send SQL command to database 
9 row=cursor.fetchone()
10 while row:
11     print row[0]
12     row=cursor.fetchone()
13 conn.close()

Through the loop command, the obtained results are displayed one by one.

Click Run to execute the program, and the query result of the SQL command can be returned normally.

The following uses the insert command in the SQL language to change the database operated in the previous code from "master" to "test", and the query command followed by cursor.execute is changed to an insert command in insert format:

1  import pymssql
 2  
3 server= " 127.0.0.1 "   #Server IP or server name 
4 user= " sa "            #The account used to log in to the database 
5 password= " password "  #The account password 
6 conn=pymssql.connect(server,user, password,database= ' test ' )
 7 cursor= conn.cursor()
 8 cursor.execute( " insert into dbo.test ([NO.],Name,Address) values ​​('003','Zhang San','Zhengzhou ') " )

After executing the command, no data is inserted into the database. This is because when executing the update, insert and delete commands, a conn.commit() command needs to be added to allow the database to execute the statement.

1  import pymssql
 2  
3 server= " 127.0.0.1 "   #Server IP or server name 
4 user= " sa "            #The account used to log in to the database 
5 password= " password "  #The account password 
6 conn=pymssql.connect(server,user, password,database= ' test ' )
 7 cursor= conn.cursor()
 8 cursor.execute( " insert into dbo.test ([NO.],Name,Address) values ​​('003','Zhang San','Zhengzhou ') " )
 9  conn.
commit()
10conn.close()

It should be noted that pymssql cannot open databases named in Chinese, so when using pymsslq to interact with the database, the accessed database must be a database named in English.

When using py2exe or pyinstaller to package and write a python program, you need to add import decimal at the beginning of the program and import the decimal template, otherwise an error will be reported when running.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326661591&siteId=291194637