Python DB-API使用流程:
- 引入API模块。
- 获取与数据库的连接。
- 执行SQL语句和存储过程。
- 关闭数据库连接。
1 def mysql_dbtest(): 2 3 config = { 4 'host':"192.168.0.6", 5 'user':"root", 6 'db':"test_lwh", 7 'passwd': "asdasd", 8 'port':3306, 9 'charset':'utf8' #中文在数据库中乱码问题,gb2312汉字处理编码 10 } 11 12 db = MySQLdb.connect(**config) 13 # db.select_db('mysql_test') 选择数据库 14 # db.autocommit(True) # db.autocommit(1) 事物性自动提交 15 16 cursor = db.cursor() 17 sql = "sql语句XXXXXX" 18 19 cursor.execute(sql) 20 # results = cursor.fetchall() #获取所有数据 21 # results = cursor.fetchmany(10) #获取10条数据 22 # results = cursor.fetchone() #获取1条数据. 23 try: 24 result = db.commit() 25 rt = db.autocommit(True) 26 except: 27 db.rollback() #失败回滚 28 29 cursor.close() #python是解释执行,建立数据库连接后,会占用解释器线程,当你不关闭连接时,那么这个线程一直占用,会使执行其他程序变慢 30 db.close() 31 return False 32 33 if __name__ == '__main__': 34 rt = mysql_dbtest() 35 print(rt)
参考链接地址:https://www.cnblogs.com/conanwang/p/6028110.html