提示信息

python 连接Mysql数据库

分界线" 已关注
  1. #!/usr/bin/python
  2. # -*- coding: UTF-8 -*-
  3. import MySQLdb
  4. # 打开数据库连接
  5. db = MySQLdb.connect("127.0.0.1", "account", "passwd", "user", charset='utf8' )
  6. # 使用cursor()方法获取操作游标
  7. cursor = db.cursor()
  8. # SQL 查询语句
  9. sql = "select * from user_01 limit 20"
  10. try:
  11. # 执行SQL语句
  12. cursor.execute(sql)
  13. # 获取所有记录列表
  14. results = cursor.fetchall()
  15. for row in results:
  16. fname = row[0]
  17. lname = row[1]
  18. age = row[2]
  19. sex = row[3]
  20. income = row[4]
  21. # 打印结果
  22. print "fname=%s,lname=%s,age=%s,sex=%s,income=%s" % (fname, lname, age, sex, income )
  23. except Exception,e:
  24. print e.message
  25. print "Error: unable to fecth data"
  26. # 关闭数据库连接
  27. db.close()
    遇到难题? "AI大模型GPT4.0、GPT" 是你的私人解答专家! 点击按钮去提问......
分界线" 关注 已关注

最近一次登录:2023-10-09 18:36:26   

暂时还没有签名,请关注我或评论我的文章
×
免费图表工具,画流程图、架构图