为了搭建一个简单的公司网站,租了一个 阿里云 云虚拟主机, 附带有数据库,虽然目前暂时用不上,但是作为一个测试平台也是极好的。
python 连接MSSQL 需要 pymssql, 不过安装老是失败, 乱翻一气发现目前pymssql只支持到 python3.7 ,可怜错误提示信息也不明说, 把3.8.5卸载最新装就顺利了。坑坑坑!!!
阿里云控制台可以查看到数据库的账号信息,基本上按这个网页介绍就可以成功连接了https://www.cnblogs.com/baxianhua/p/10584133.html
import pymssql
conn=pymssql.connect(host='xxxx.my3w.com',user='xxxx',password='xxxx',database='xxxx_db',charset='utf8')
cursor = conn.cursor()
print(conn)
print(cursor)
print('connect to db success')
#创建表,删除表
cursor.execute("""
IF OBJECT_ID('test1','U') IS NOT NULL
DROP TABLE test1
CREATE TABLE test1(
tid INT NOT NULL,
age int,
school VARCHAR(150),
PRIMARY KEY(tid))
""")
conn.commit()
cursor.close()
conn.close()
2.写点数据
import pymssql
conn=pymssql.connect(host='xxxx.my3w.com',user='xxxx',password='xxxx',database='xxxx_db',charset='utf8')
cursor = conn.cursor()
print(conn)
print(cursor)
print('connect to db success')
#插入数据
cursor.executemany(
"insert into test1 values(%d,%d,%s)",
[
(10001,5,'qiuhua school'),
(10002,4,'chunhua school'),
(10003,6,'qiu school'),
(10004,5,'qiuhua school'),
(10005,4,'chunhua school'),
(10006,6,'qiu school'),
(10007,5,'qiuhua school'),
(10008,4,'chunhua school'),
(10009,6,'qiu school'),
(10010,5,'qiuhua school'),
(10011,4,'chunhua school'),
(10012,6,'qiu school'),
(10013,5,'qiuhua school'),
(10014,5,'qiuhua school'),
(10015,4,'chunhua school'),
(10016,6,'qiu school'),
(10017,5,'qiuhua school'),
(10018,4,'chunhua school'),
(10019,6,'qiu school'),
(10020,6,'qiu school')
]
)
conn.commit()
import pymssql
conn=pymssql.connect(host='xxxx.my3w.com',user='xxxx',password='xxxx',database='xxxx_db',charset='utf8')
cursor = conn.cursor()
print(conn)
print(cursor)
print('connect to db success')
#查询
# cursor.execute('select * from test1 where school=%s','qiuhua school')
# cursor.execute('select * from test1 where age>= %s','5')
cursor.execute('select * from test1 where tid>= %s','10015')
for row in cursor:
print(row)
print('query success')
cursor.close()
conn.close()
最后查询结果大概这样子:有个警告但不影响结果
Python 3.7.0 (v3.7.0:1bf9cc5093, Jun 27 2018, 04:59:51) [MSC v.1914 64 bit (AMD64)] on win32
Type "copyright", "credits" or "license()" for more information.
>>>
===== RESTART: Z:\Python\python pymssql\mssql_query.py =====
Warning (from warnings module):
File "Z:\Python\python pymssql\mssql_query.py", line 4
import pymssql
DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated, and in 3.8 it will stop working
<pymssql.Connection object at 0x000002059A28DD48>
<pymssql.Cursor object at 0x000002059A275DC8>
connect to db success
(10015, 4, 'chunhua school')
(10016, 6, 'qiu school')
(10017, 5, 'qiuhua school')
(10018, 4, 'chunhua school')
(10019, 6, 'qiu school')
(10020, 6, 'qiu school')
query success
>>>