本文主要介绍Python连接SQL Serverxwenw.com/tag/%e6%95%b0%e6%8d%ae%e5%ba%93" target="_blank">数据库(MSSQL)。

一、安装PyMsSql库

使用命令: pip install pymssql

340-1.png

二、连接测试

import pymssql
 
# 打开数据库连接
db = pymssql.connect(
         host='77bx.com',
         port=1433,
         user='sa',
         password='77bx.com',
         database='77bx.com'
         )

# 使用 cursor() 方法创建一个游标对象 cursor
cursor = db.cursor()
 
# 使用 execute()  方法执行 SQL 查询 
cursor.execute("SELECT SERVERPROPERTY('edition')")
 
# 使用 fetchone() 方法获取单条数据.
data = cursor.fetchone()
 
print ("Database version : %s " % data)
 
# 关闭数据库连接
db.close()

三、数据库操作

1、查询操作

import pymssql
 
# 打开数据库连接
db = pymssql.connect(
         host='77bx.com',
         port=1433,
         user='sa',
         password='77bx.com',
         database='77bx.com'
         )

# 使用 cursor() 方法创建一个游标对象 cursor
cursor = db.cursor()

# SQL 查询语句
sql = "SELECT * FROM xzy_user WHERE username= '%s'" % ('77bx')

try:
    # 使用 execute()  方法执行 SQL 查询 
    cursor.execute(sql)

    # 使用 fetchall() 方法获取所有记录列表.
    data = cursor.fetchall()
    for row in data:
        print(row)
except:
    print("Error: cannot fetch data");
 
# 关闭数据库连接
db.close()

2、更新操作

import pymssql
 
# 打开数据库连接
db = pymssql.connect(
         host='77bx.com',
         port=1433,
         user='sa',
         password='77bx.com',
         database='77bx.com'
         )

# 使用 cursor() 方法创建一个游标对象 cursor
cursor = db.cursor()

# SQL 更新语句
sql = "UPDATE xzy_user SET username = '%s' WHERE id = '%s'" % ('77bx',1000)

try:
   # 执行SQL语句
   cursor.execute(sql)
   # 提交到数据库执行
   db.commit()
except:
   # 发生错误时回滚
   db.rollback()
 
# 关闭数据库连接
db.close()

3、插入操作

import pymssql
 
# 打开数据库连接
db = pymssql.connect(
         host='77bx.com',
         port=1433,
         user='sa',
         password='77bx.com',
         database='77bx.com'
         )

# 使用 cursor() 方法创建一个游标对象 cursor
cursor = db.cursor()

# SQL 插入语句
sql = "INSERT INTO xzy_user(username, password, status) VALUES ('%s', '%s',  '%s')" % ('77bx', '77bx','vip')

try:
   # 执行SQL语句
   cursor.execute(sql)
   # 提交到数据库执行
   db.commit()
except:
   # 发生错误时回滚
   db.rollback()
 
# 关闭数据库连接
db.close()

4、删除操作

import pymssql
 
# 打开数据库连接
db = pymssql.connect(
         host='77bx.com',
         port=1433,
         user='sa',
         password='77bx.com',
         database='77bx.com'
         )

# 使用 cursor() 方法创建一个游标对象 cursor
cursor = db.cursor()

# SQL 删除语句
sql = "DELETE FROM xzy_user WHERE username = '%s'" % ('77bx')

try:
   # 执行SQL语句
   cursor.execute(sql)
   # 提交到数据库执行
   db.commit()
except:
   # 发生错误时回滚
   db.rollback()
 
# 关闭数据库连接
db.close()
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。