linux python2.7连接mysql
时间: 2023-10-13 13:18:32 浏览: 87
可以使用MySQL-Python或者PyMySQL模块来连接MySQL数据库。以下是使用PyMySQL模块连接MySQL数据库的示例代码:
```python
import pymysql
# 打开数据库连接
db = pymysql.connect(host="localhost", user="root", password="password", database="test")
# 使用 cursor() 方法创建一个游标对象 cursor
cursor = db.cursor()
# 使用 execute() 方法执行 SQL 查询
cursor.execute("SELECT VERSION()")
# 使用 fetchone() 方法获取单条数据.
data = cursor.fetchone()
print("Database version : %s " % data)
# 关闭数据库连接
db.close()
```
需要注意的是,使用PyMySQL模块需要先安装,可以使用pip进行安装:
```
pip install PyMySQL
```
另外,如果你要在Python2.7中使用MySQL-Python模块,可以参考以下示例代码:
```python
import MySQLdb
# 打开数据库连接
db = MySQLdb.connect("localhost", "root", "password", "test")
# 使用cursor()方法获取操作游标
cursor = db.cursor()
# SQL 查询语句
sql = "SELECT * FROM EMPLOYEE WHERE INCOME > %s" % (1000)
try:
# 执行SQL语句
cursor.execute(sql)
# 获取所有记录列表
results = cursor.fetchall()
for row in results:
fname = row[0]
lname = row[1]
age = row[2]
sex = row[3]
income = row[4]
# 打印结果
print "fname=%s,lname=%s,age=%d,sex=%s,income=%d" % \
(fname, lname, age, sex, income)
except:
print "Error: unable to fecth data"
# 关闭数据库连接
db.close()
```
同样需要先安装MySQL-Python模块:
```
pip install MySQL-python
```
阅读全文
相关推荐


















