手机版
你好,游客 登录 注册
背景:
阅读新闻

Python 简单的MySQL数据库操作

[日期:2016-11-12] 来源:Linux社区  作者:Linux [字体: ]

1、首先需要下载安装MySQL-python模块

2、数据库的操作流程

Python的DB-API,为大多数的数据库实现了接口,使用它连接各数据库后,就可以用相同的方式操作各数据库。

  1. Python DB-API使用流程: 引入 API 模块
  2. 获取与数据库的连接
  3. 执行SQL语句和存储过程
  4. 关闭数据库连接

测试代码:

# -*- encoding: utf-8 -*-

import MySQLdb
testdb=MySQLdb.connect(host="localhost", user = "root", passwd="1234",port = 3306,charset='utf8')
testdb.select_db('test')
cur = testdb.cursor() # 获取游标

Title = "Title test"
PublishTime = "2015-12-15 05:18:00"
Keyword = '乌镇'

sql = "INSERT INTO test.news(Title, PublishTime, Keyword) \
        VALUES (%s,%s,%s)"
try:
    cur.execute(sql,(Title, PublishTime, Keyword))
    testdb.commit()
except Exception,e:
    # Rollback in case there is any error
    testdb.rollback()
    print e
testdb.commit()
# 关闭连接
cur.close()
testdb.close()

连接过程可能出现的问题:

  1. 2003, “Can’t connect to MySQL server on ‘localhost’ (10061)”
    a、该问题的原因有可能是MySQL本地服务的问题,这种情况下只要检查下本地服务中相应的服务有没有开启即可;
    b、另一种情况是由于hosts文件中的设置的localhost对应的IP不对,检查一下,设置为
    127.0.0.1 localhost
    即可,并且将这一行
    ::1 localhost注释掉

  2. 数据库插入、读取中文乱码问题
    需要保证Python代码、连接时候的编码、MySQL设置都为utf8,其中Python中的代码设置为:

# -*- encoding: utf-8 -*-

连接时的编码设置

connect=MySQLdb.connect(host="localhost", user = "root", passwd="1234",port = 3306,charset='utf8')

本文永久更新链接地址http://www.linuxidc.com/Linux/2016-11/137043.htm

linux
相关资讯       Python操作MySQL数据库 
本文评论   查看全部评论 (0)
表情: 表情 姓名: 字数

       

评论声明
  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款