4321ddd 发表于 2016-11-25 08:33:46

用python操作mysql数据库(之简单查询操作)

1、mysql安装
    此处省略一万字.......

2、pip安装MySQLdb模块
sudo pip install mysql-python

3、简单代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import MySQLdb

#建立连接
conn = MySQLdb.connect(host='127.0.0.1',user='root',passwd='1qaz#EDC',db='test_db')
cur = conn.cursor() #创建一个游标
#说明,connect方法生成一个连接对象,通过这个对象来访问到数据库

#对数据进行操作
res = cur.execute('select * from UserInfo') #执行sql语句
data = cur.fetchall()   #读取执行结果

#关闭数据库连接
cur.close()
conn.close()

print res #打印出共有多少条数据
print data #打印数据的实际内容





4、查询指定ID号的数据

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import MySQLdb

#建立连接
conn = MySQLdb.connect(host='127.0.0.1',user='root',passwd='1qaz#EDC',db='test_db')
cur = conn.cursor()

#对数据进行操作
sql = "select * from user where id=%s" #定义sql语句
params = ('3')    #参数 ID为3

cur.execute(sql,params)    #执行sql语句
data = cur.fetchall()

#关闭数据库连接
cur.close()
conn.close()

print data



页: [1]
查看完整版本: 用python操作mysql数据库(之简单查询操作)