python连接sqlserver操作增删改查(图文教程)
python连接sqlserver操作增删改查
pip install pyodbc
查看案例>>
import cgi
import pyodbc
import socket
print("Content-type:text/html;charset=gb2312\r\n")
print("<html>")
print("<head><title>python连接sqlserver操作增删改查</title></head>")
print("<body>")
# 获取当前用户的IP地址
ip = socket.gethostbyname(socket.gethostname())
# 提取字符串中的前8位
result = ip[:8]
# 输出结果
# print("前8位是:", result)
# if not result=="192.168.":
if 1==2:
print("ip("+str(ip)+")地址不是本地")
else:
# 连接字符串,包含连接数据库所需的信息
conn_str = (
r'DRIVER={SQL Server};'
r'SERVER=localhost;'
r'DATABASE=数据库名;'
r'UID=sa;'
r'PWD=密码;'
)
# 连接到数据库
conn = pyodbc.connect(conn_str)
# 创建游标
cursor = conn.cursor()
# 获取URL中的参数
params = cgi.FieldStorage()
# 获取参数值
act = params.getvalue('act')
id = params.getvalue('id')
bodycontent = params.getvalue('bodycontent')
# form = cgi.FieldStorage()
# # 获取 title 字段的值
# bodycontent = form.getvalue('bodycontent')
if act:
if act=="submit":
if bodycontent:
# 插入数据
sql = "INSERT INTO xy_xiyueta (bodycontent) VALUES ('"+str(bodycontent)+"')"
if id:
sql = "UPDATE xy_xiyueta SET bodycontent = '"+str(bodycontent)+"' WHERE id="+str(id)
print("sql="+sql+"<br>")
cursor.execute(sql)
# 提交事务
conn.commit()
else:
print("请输入内容")
elif act=="del":
if id:
sql = "DELETE FROM xy_xiyueta WHERE id = "+str(id)
cursor.execute(sql)
# 提交事务
conn.commit()
elif act=="edit":
if id:
sql = "SELECT * FROM xy_xiyueta WHERE id = "+str(id)
# print(sql)
cursor.execute(sql)
# 读取查询结果
for row in cursor:
bodycontent=row.bodycontent
# 执行SQL查询
cursor.execute('SELECT * FROM xy_xiyueta')
print("<a href='?act=showadd'>添加</a> | ")
print("<hr><br>")
if act=="showadd" or act=="edit":
if not bodycontent:
bodycontent=""
if not id:
id=""
print('<form id="form1" name="form1" method="post" action="?act=submit&id='+str(id)+'"> 内容: <input type="text" value="'+str(bodycontent)+'" name="bodycontent" id="bodycontent" /> <input type="submit" name="button" id="button" value="提交" /></form>')
# 读取查询结果
for row in cursor:
print(row.bodycontent,row.createtime,"<a href='?act=del&id="+str(row.id)+"' onclick=\"if(confirm('确认删除?')==false)return false;\">删除</a> | <a href='?act=edit&id="+str(row.id)+"'>修改</a><br>")
# 关闭游标和连接
cursor.close()
conn.close()
在cmd里运行代码
import pyodbc
# 连接字符串,包含连接数据库所需的信息
conn_str = (
r'DRIVER={SQL Server};'
r'SERVER=localhost;'
r'DATABASE=数据库名称;'
r'UID=sa;'
r'PWD=密码;'
)
# 连接到数据库
conn = pyodbc.connect(conn_str)
# 创建游标
cursor = conn.cursor()
# 执行SQL查询
cursor.execute('SELECT * FROM xy_admin')
# 读取查询结果
for row in cursor:
print(row)
# 关闭游标和连接
cursor.close()
conn.close()