python连接mysql比较顺利,网上很多代码,连接sqlserver的例子少,且很多错误,尝试很多帖子,最后成功代码如下。
#连接mysql import pymysql def conn(): try: connection = pymysql.connect(host='localhost',port=3306,user='root', password='123456', database='cl') print("连接成功!") return connection except pymysql.OperationalError as e: print(f"错误:{e}") return None #连接sqlserver 注意pymssql版本,版本不要过高,现阶段版本为2.2.6 import pymssql def connSQLServer(): try: connection = pymssql.connect(host='localhost',port='1433',server='LAPTOP-5KJHE745',user='sa', password='123456', database='bookDB') print("连接成功!") return connection except pymssql.OperationalError as e: print(f"错误:{e}") return None if __name__ == '__main__': #conn = conn() #连接mysql conn=connSQLServer() if conn: # 使用连接执行查询等操作 cursor = conn.cursor() #cursor.execute("SELECT * FROM c_user") #查询mysql cursor.execute("SELECT * FROM t_book") rows = cursor.fetchall() for row in rows: print(row) conn.close()
标签:__,python,cursor,mysql8,sqlserver2012,mysql,print,连接,conn From: https://www.cnblogs.com/wangyuna7723/p/18001536