python操作mysql 数据查询


安装pymysql模块:pip install pymysq

 

 1 from pymysql import *
 2 
 3 def main():
 4     # 第一步 创建connect连接
 5     conn = connect(host="localhost",port=3306,user="root",password="",database="jing_dong",charset="utf8")
 6     # 第二部获取cursor对象(游标对象)
 7     cs1 = conn.cursor()
 8     

    中间是自由操作,上面两句和下面两句是必须创建的,通过execute执行mysql语句:
   cs1.execute('select * from jing_dong')
   如果是一个查询语句,查询结果就保存在游标对象中,用fetch*获取
   cs1.fetch* 取得查询返回数据 fetch有几种:
   fetchone()、fetchmany()、fetchall()
   fetchone()每次返回一条记录,以元组的形式,fetchmany()是自定义返回记录数目,返回的每一个元组包含在一个大元组中
   获取记录时,无论用什么fetch,获取记录就像读取文件那个指针一样,第二次执行,会接着上一次fetch结束的位置开始,当把所有
   记录获取之后,再fetch就获取不到记录了

9 10 #g关闭cursor对象 11 cs1.close() 12 conn.close() 13 14 15 if __name__ == "__main__": 16 main()

 

下面是一个查询示例:

 1 from pymysql import *
 2 
 3 def main():
 4     # 创建connect连接
 5     conn = connect(host="localhost",port=3306,user="root",password="",database="jing_dong",charset="utf8")
 6     #获取cursor对象
 7     cs1 = conn.cursor()
 8 
 9     # count 返回的是表的行数,查询结果保存在游标对象cs1中
10     count = cs1.execute("select * from goods")
11 
12     for i in range(count):
13         print(cs1.fetchone())
14 
15 
16     #g关闭cursor对象
17     cs1.close()
18     conn.close()
19 
20 
21 if __name__ == "__main__":
22     main()

 

下面又是一个代码演练:

 1 from pymysql import connect
 2 
 3 class JD(object):
 4     def __init__(self):
 5         self.conn = connect(host="localhost",port=3306,user="root",password="",database="jing_dong",charset="utf8")
 6         self.cs1 = self.conn.cursor()
 7 
 8     @staticmethod
 9     def print_msg():
10         print("-------JING DONG---------")
11         print("1 查询所有数据")
12         print("2、查询所有品牌")
13         print("3、查询所有分类")
14         return input("请选择:")
15    
    #当程序死掉的时候会自动调用此方法 16 def __del__(self): 17 self.cs1.close() 18 self.conn.close() 19 20 def exe_sql(self,sql): 21 self.cs1.execute(sql) 22 for i in self.cs1.fetchall(): 23 print(i) 24 25 def show_cate(self): 26 sql = "select name from goods_cates" 27 self.exe_sql(sql) 28 29 def show_brand(self): 30 sql = "select name from goods_brands" 31 self.exe_sql(sql) 32 33 def show_all(self): 34 sql = "select * from goods" 35 self.exe_sql(sql) 36 37 def run(self): 38 while True: 39 num = self.print_msg() 40 if num == "1": 41 self.show_all() 42 elif num == "2": 43 self.show_brand() 44 elif num == "3": 45 self.show_cate() 46 else: 47 print("wrong input...try again....") 48 49 def main(): 50 jd = JD() 51 jd.run() 52 if __name__ == "__main__": 53 main()

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM