Linux下使用SQLServer
程序员文章站
2024-02-23 00:02:46
...
1. 说明
SQL Server是由Microsoft开发和推广的关系数据库管理系统。本文介绍在Ubuntu系统下,SQL Server服务端及客户端的安装,基本命令及如何使用python访问数据。
2. 安装
由于SQLServer不在默认安装的软件源之中,在Ubuntu 16.04上,需要先加入其软件源,安装后再进行一些配置
(1) SQLServer服务器端
$ wget -qO- https://packages.microsoft.com/keys/microsoft.asc | sudo apt-key add - #导入公钥
$ sudo add-apt-repository "$(wget -qO- https://packages.microsoft.com/config/ubuntu/16.04/mssql-server-2017.list)"
$ sudo apt-get update
$ sudo apt-get install -y mssql-server
$ sudo apt-get -f install
$ sudo /opt/mssql/bin/mssql-conf setup # 配置:输入密码并记住此密码
$ systemctl stop mssql-server # 为修改排序规则,先关掉服务
$ sudo /opt/mssql/bin/mssql-conf set-collation # 输入规则:Chinese_PRC_CI_AS
$ systemctl enable mssql-server && systemctl start mssql-server # 重启服务
(2) SQLServer命令行工具
$ sudo sh -c "curl https://packages.microsoft.com/keys/microsoft.asc | sudo apt-key add -"
$ sudo sh -c "echo deb [arch=amd64] https://packages.microsoft.com/ubuntu/16.04/mssql-serverxenial main > /etc/apt/sources.list.d/sql-server.list"
$ $sudo sh -c "echo deb [arch=amd64] https://packages.microsoft.com/ubuntu/16.04/prod xenial main >>/etc/apt/sources.list.d/sql-server.list"
$ sudo apt-get update
$ sudo apt-get install -y mssql-tools-y
$ dpkg -L mssql-tools # 看一下安装在哪个目录了,我的机器是安装在/opt目录下了 $ /opt/mssql-tools/bin/sqlcmd -S localhost -U SA -P 密码 # 试运行一下, 默认用户名SA
(3) SQLServer的Python支持包
$ sudo pip install pymssql
3. SQLServer基本命令
$ /opt/mssql-tools/bin/sqlcmd -S localhost -U SA -P 密码 # 用命令行连接
(1) 建库
> create database testme
> go
(2) 看当前数据库列表
> select * from SysDatabases
> go
(3) 看当前数据表
> use 库名
> select * from sysobjects where xtype='u'
> go
(4) 看表的内容
> select * from 表名;
> go
4. Python程序访问SQLServer数据库
import pymssql
server = 'localhost'
user = 'sa'
password = 密码
database = 'testme'
conn = pymssql.connect(server, user, password, database)
cursor = conn.cursor()
cursor.execute("""
IF OBJECT_ID('persons', 'U') IS NOT NULL
DROP TABLE persons
CREATE TABLE persons (
id INT NOT NULL,
name VARCHAR(100),
salesrep VARCHAR(100),
PRIMARY KEY(id)
)
""")
cursor.executemany(
"INSERT INTO persons VALUES (%d, %s, %s)",
[(1, 'John Smith', 'John Doe'),
(2, 'Jane Doe', 'Joe Dog'),
(3, 'Mike T.', 'Sarah H.')])
conn.commit()
cursor.execute('SELECT * FROM persons WHERE salesrep=%s', 'John Doe')
row = cursor.fetchone()
while row:
print("ID=%d, Name=%s" % (row[0], row[1]))
row = cursor.fetchone()
conn.close()
5. 参考
(1) [学习笔记]Ubuntu下安装配置SQLSERVER2017
https://www.cnblogs.com/jinanxiaolaohu/p/8296603.html
(2) 如何在Linux上安装和使用MS SQL Server
https://blog.csdn.net/cdshrewd/article/details/53386215
(3) Python连接SQL Server数据库 - pymssql使用基础
https://www.cnblogs.com/baiyangcao/p/pymssql_basic.html
(4) sqlcmd介绍
https://www.cnblogs.com/shanwater/p/6560702.html
(5) python连接sqlserver和MySQL实现增删改查
https://www.cnblogs.com/hiwuchong/p/9096542.html
上一篇: SqlServer缓存依赖实例