First, to download the Pymssql module to http://pymssql.sourceforge.net/, this module must be installed before you can connect MySQL with Python
The following is a SQL Server operation code that requires attention to the character set
#-*-coding:utf-8-*-Import pymssql# Create a database connection, host is the IP address of the server, if the machine can be used".", user is the access username, password is the password, database is the name Conn=pymssql.connect (host=".", user="SA", password="123456", database="Test") #创建游标对象, equivalent to ADO recordset Cou=conn.cursor () SQL="Select Name,age from student"#执行命令cou. Execute (SQL) #取出所有记录, the element that returns a list,list that contains a tuple is a record row, the element of a tuple is the field of each row of records for(Name,age)inchcou.fetchall (): Print"Name:"+name+", Age:"+Str (age) #注意, need to be converted to string type, or formatted to output SQL="Insert into student (name,age,address) VALUES (' admin ', ' 88 ', ' Wuhan ')"#插入一条记录cou. Execute (SQL) #只有执行了下面的命令, the above actions take effect, with exception handling, you can implement PYMSSQL transaction Operations Conn.commit () #关闭数据库的连接conn. Close ()
Sample code for Python to connect to a SQL Server database