python 和 mysql连接

python 和 mysql连接

虫师教程:http://www.cnblogs.com/fnng/p/3565912.html

其他教程pymysql:http://www.cnblogs.com/lcj0703/p/5712788.html

第一步,下载源代码:

# 请下载zip源代码,这样才可以编译
https://pypi.python.org/pypi/MySQL-python/1.2.5

# 我的版本从2.7升级到3.5.2的时候,上面那个就无效了。我使用了这个
https://pypi.python.org/pypi/PyMySQL

第二步,解压并且进入目录,输入编译命令:python setup.py install

如果编译有问题,根据指示解决

复制代码
1、如需要c++
   https://www.microsoft.com/en-us/download/confirmation.aspx?id=44266

2、如果出现这个错误:_mysql.c(42) : fatal error C1083: Cannot open include file: 'config-win.h': No such file or directory
error: command 'C:\Users\qinwanxia\AppData\Local\Programs\Common\Microsoft\Visual C++ for Python\9.0\VC\Bin\cl.exe' failed with exit status 2
   需要下载并安装MySQL connector 32位,系统是64位的也需要安装32位:https://dev.mysql.com/downloads/connector/c/6.0.html#downloads
复制代码

第三步,进入python命令行模式,检查是否包是否可引用:

python

import MySQLdb 
# 或者
import pymysql

第四步,在程序中使用mysql:

复制代码
#coding=utf-8
import MySQLdb

conn= MySQLdb.connect(
        host='localhost',
        port = 3306,
        user='root',
        passwd='123456',
        db ='test',
        )
cur = conn.cursor()

#创建数据表
#cur.execute("create table student(id int ,name varchar(20),class varchar(30),age varchar(10))")

#插入一条数据
#cur.execute("insert into student values('2','Tom','3 year 2 class','9')")


#修改查询条件的数据
#cur.execute("update student set class='3 year 1 class' where name = 'Tom'")

#删除查询条件的数据
#cur.execute("delete from student where age='9'")

cur.close()
conn.commit()
conn.close()
复制代码

pymysql版本

import pymysql

#连接数据库
conn = pymysql.connect(host='192.168.8.208', port=3306,user = 'root', passwd='tuandai_bm2015', db='tuandai_bm')

#创建游标
cur = conn.cursor()

#查询lcj表中存在的数据
cur.execute("select * from tb_parameter where para_type='version' and para_name='H5'");

#fetchall:获取lcj表中所有的数据
ret1 = cur.fetchall()

print(ret1)

 设置pymysql默认字符集类型

找到C:Python27Libsite-packagespymysql安装目录,使用文本编辑器(如notepad++)打开connections.py,我的在550行有这样一句话,你想使用的字符集。

原文地址:https://www.cnblogs.com/CyLee/p/7421492.html