python 操作mysql 入门

本文提供了一个使用Python连接MySQL数据库并执行查询的简单示例。示例中定义了一个名为SQLdb的类,该类初始化了一个SQL查询语句,并通过Conn方法尝试连接到指定的数据库,执行SQL查询并打印结果。
 1 # -*- coding: utf-8 -*-
 2 """
 3 Created on Fri Oct 30 10:39:23 2015
 4 @author: zenwan
 5 """
 6 import MySQLdb
 7 from pprint import pprint
 8 
 9 
10 class SQLdb:
11     def __init__(self):
12         self.sql0 = 'SELECT  bigtopic FROM user_topic'
13 
14     def Conn(self):
15         try:
16             conn = MySQLdb.connect(host='10.10.20.165',
17                                    user='user',
18                                    passwd='@user123',
19                                    db='userdata',
20                                    charset='utf8',
21                                    port=3306)
22             cur = conn.cursor()
23             cur.execute(self.sql0)
24             result0 = cur.fetchall()
25             pprint(result0)
26             print type(result0)
27             cur.close()
28             conn.close()
29             return result0
30 
31         except MySQLdb.Error, e:
32             print "MySQLdb ERROR :%s" % (e)
33 
34 if __name__ == '__main__':
35     s = SQLdb()
36     s.Conn()

 

转载于:https://www.cnblogs.com/zenzen/p/4923307.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值