利用pymssql连接sqlserver进行数据存储

import pymssql
conn = pymssql.connect(host = ' ', user = ' ', password = ' ', database = 'spider')
cursor = conn.cursor()
if not cursor:
    print('数据库连接失败!')
else:
    cursor.execute('use spider')
    print('数据库连接成功!')
#sql = 'CREATE TABLE students(no varchar (20) NOT NULL, name nvarchar (20) NOT NULL, age int NOT NULL, primary key(no))'
#cursor.execute(sql)
data = {
    'no': '12345678',
    'name': '李明',
    'age': '3'
}
table = 'students'
keys = ','.join(data.keys())
values = ','.join(['%s'] * len(data))
sql = 'INSERT INTO {table}({keys}) VALUES ({values})'.format(table = table, keys = keys, values = values)
print(sql)
#数据库插入操作
try:
    cursor.execute(sql, tuple(data.values()))
    conn.commit()
    print('INSERT SUCCESSFUL!')
except:
    print('INSERT FAILED!')
    conn.rollback()
#数据库查询操作
try:
    cursor.execute('SELECT * FROM students')
    rows = cursor.fetchall()
    print('数据列表:\n')
    for row in rows:
        print('NO:%s, name:%s, age:%s' % (row[0], row[1], row[2]))
except:
    print('查询失败!')
conn.close()

问题:
连接数据库、查询数据库正常,但无法完成建表操作
解决方案:
和在DBMS里不一样,不是AUTOCOMMIT,所以要添加执行函数commit(),否则语句并未执行

你可能感兴趣的:(学习笔记)