import pyodbc # DRIVER={SQL Server};DATABASE=数据库名;SERVER=服务器所在的计算机名,端口号;UID=你的用户名;PWD=你的密码 odbc = 'DRIVER={SQL Server};SERVER=127.0.0.1,1433;DATABASE=sqldbtest;UID=sa;PWD=123456' #1.链接数据库 db =pyodbc.connect(odbc,autocommit=True,)#使用 cursor()方法创建一个游标对象 cursor #2.游标 cursor =db.cursor()#使用 execute()方法执行 SQL 查询
#编码
conn.setencoding(encoding='utf-8')
#3.执行sql #1.查询 s1 = """ select * from test_name where name= ? """ cursor.execute(s1,("码神",)) #获取结果 res1 = cursor.fetchall() # [(2, '李四', '男', '18852671311', 19), (3, '王五', '女', '18852671303', 17)] # res2 = cursor.fetchone() #(1, '张三', '男', '18852671307', 23) # res3 = cursor.fetchmany(2) # print(res1) #结果封装成字典 a = [dict(zip([column[0] for column in cursor.description], row)) for row in res1] print(a) #2.增 a1 = """ # insert into test_name values(?,?,?,?) """ # cursor.execute(a1,("码神1","男","18852671111",21)) #5.关闭 # db.commit() # db.rollback() cursor.close() db.close()
参考:https://blog.csdn.net/chroming/article/details/51541959