python2.7连接mysql
时间: 2023-09-04 22:06:45 浏览: 43
在Python 2.7中连接MySQL需要使用MySQLdb库。首先需要安装MySQLdb库,可以使用以下命令:
```pip install MySQL-python```
然后可以使用以下代码连接MySQL:
```python
import MySQLdb
# 打开数据库连接
db = MySQLdb.connect(host="localhost",user="username",passwd="password",db="dbname",charset="utf8")
# 使用cursor()方法获取操作游标
cursor = db.cursor()
# SQL 查询语句
sql = "SELECT * FROM table"
# 执行SQL语句
cursor.execute(sql)
# 获取所有记录列表
results = cursor.fetchall()
# 输出记录
for row in results:
print(row)
# 关闭数据库连接
db.close()
```
其中,需要替换的参数有:
- host:MySQL服务器地址
- user:MySQL用户名
- passwd:MySQL用户密码
- db:要连接的数据库名称
- charset:字符集,一般使用utf8
另外,还需要根据具体的情况修改SQL查询语句。
相关问题
linux python2.7连接mysql
可以使用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
```
centos7 上的python2.7安装pymysql
可以通过以下步骤在 CentOS 7 上安装 Python 2.7 和 PyMySQL:
1. 确认当前系统是否已安装 Python 2.7:
```
python2.7 -V
```
如果已经安装,继续进行下一步。否则,您需要先安装 Python 2.7,可以使用以下命令安装:
```
sudo yum install -y python27
```
2. 安装 Pip:
```
sudo yum install -y python27-pip
```
3. 安装 PyMySQL:
```
sudo python2.7 -m pip install PyMySQL
```
现在,您可以使用 PyMySQL 在 Python 2.7 中连接和操作 MySQL 数据库了。