python 操作mysql 入门

 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()

 

posted @ 2015-10-30 15:00  zeNlp  阅读(134)  评论(0编辑  收藏  举报