且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2022-09-11 16:22:53

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


本文转自 TtrToby 51CTO博客,原文链接:http://blog.51cto.com/freshair/1876055