python连接sqlserver数据库

1.准备工作

python3.6连接sqlserver数据库需要引入pymssql模块

pymssql官方:https://pypi.org/project/pymssql/

没有安装的话需要:

pip安装:

pip install pymssql

2.连接数据库

首先你得明确目标数据库的:'服务器名称',"账户名称","密码","数据库名称"

因为这些是必要的参数

这里使用本地数据库做测试:

下面是链接语句:

复制代码
import pymssql #引入pymssql模块


def conn():
    connect = pymssql.connect('(local)', 'sa', '**********', 'test') #服务器名,账户,密码,数据库名
    if connect:
        print("连接成功!")
    return connect


if __name__ == '__main__':
    conn = conn()
复制代码

运行结果:

连接成功!

Process finished with exit code 0

3.增删改查(CRUD)

    创建一个新数据库表:

复制代码
import pymssql

connect = pymssql.connect('(local)', 'sa', 'password1633', 'test')  #建立连接
if connect:
    print("连接成功!")
    
cursor = connect.cursor()   #创建一个游标对象,python里的sql语句都要通过cursor来执行
cursor.execute("create table C_test02(id varchar(20))")   #执行sql语句
connect.commit()  #提交
cursor.close()   #关闭游标
connect.close()  #关闭连接
复制代码

注意当执行更改数据库表的操作时,执行完sql后别忘记加一句commit().

close()是必须的,否则python程序会一至占用这个数据库.

增加(Create):

复制代码
import pymssql

connect = pymssql.connect('(local)', 'sa', 'password1633', 'test')  #建立连接
if connect:
    print("连接成功!")
    
cursor = connect.cursor()   #创建一个游标对象,python里的sql语句都要通过cursor来执行
sql = "insert into C_test (id, name, sex)values(1002, '张si', '女')"
cursor.execute(sql)   #执行sql语句
connect.commit()  #提交
cursor.close()   
connect.close()  
复制代码

运行结果:

查询(Retrieve):

复制代码
import pymssql

connect = pymssql.connect('(local)', 'sa', 'password1633', 'test')  #建立连接
if connect:
    print("连接成功!")
    
cursor = connect.cursor()   #创建一个游标对象,python里的sql语句都要通过cursor来执行
sql = "select name, sex from C_test"
cursor.execute(sql)   #执行sql语句
row = cursor.fetchone()  #读取查询结果,
while row:              #循环读取所有结果
    print("Name=%s, Sex=%s" % (row[0],row[1]))   #输出结果
    row = cursor.fetchone()

cursor.close()   
connect.close()
复制代码

运行结果:

https://www.cnblogs.com/toheart/p/9802990.html

更新(Update)和删除(Delete)的操作都大同小异.改写sql语句就行.

猜你喜欢

转载自www.cnblogs.com/lydg/p/11362971.html
今日推荐