Python 简单的MySQL数据库操作

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')

猜你喜欢

转载自www.linuxidc.com/Linux/2016-11/137043.htm