pip的安装参照:centos6 安装pip
python2.7 使用:
pip install MySQL-python
python3更推荐使用 py-mysql
本文只是简单的测试,就不对py-mysql另行研究了。
需要注意的是写代码是要非常注意代码缩进。
否则极容易报: IndentationError:expected an indented block
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import MySQLdb
class mysqlTest:
def __init__(self, host, port):
self.host = host
self.port = port
def printParam(self):
print self.host
print self.port
def connectDB(self):
# 打开数据库连接
db = MySQLdb.connect(host=self.host, port=self.port, user="root", passwd="123456", db="test", charset='utf8' )
# 使用cursor()方法获取操作游标
cursor = db.cursor()
# 使用execute方法执行SQL语句
cursor.execute("SELECT @@port")
# 使用