Sample code for Python to connect to a SQL Server database

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.