python中pandas模块实现SQL Server中的select

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/yupeigu/article/details/79249710

python连接sql server的方法,可以参考这篇文章:python连接SQL Server:Pymssql模块

基于下面的数据,分别用sql 和 python,实现数据集的关联,得到 学生、课程、成绩 的数据。

建表可以参考:python中pandas的集合关联(merge) 与SQL Server中表关联join的对比


(1)SQL Server中的select

这个是SQL中最简单的,查前3个:

 select top 3
        sname,
        ssex,
		sage
 from student

(2)pandas中实现select

# -*- coding:gbk -*-  
  
import pymssql as pm  
from pandas import DataFrame #行列结构  
import pandas as pd  
  
conn = pm.connect(host='localhost',user='sa',password='momogua',database='test')  
  
cur = conn.cursor()  
  
  
#获取student表的数据,格式化  
cur.execute('select sid,sname,ssex,sage from student')  
student = cur.fetchall()  
dstudent = DataFrame(student,columns=['sid','sname','ssex','sage'])


print dstudent[['sname','ssex','sage']].head(3)
输出结果:

>>> ================================ RESTART ================================
>>> 
  sname ssex  sage
0    刘一    男    18
1    钱二    女    19
2    张三    男    17
>>> 

猜你喜欢

转载自blog.csdn.net/yupeigu/article/details/79249710