python访问mysql将返回的表转化为json
#
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# from __future__ import print_function import os
import sys from pyspark import SparkContext
from pyspark.sql import SQLContext
from pyspark.sql.types import Row, StructField, StructType, StringType, IntegerType if __name__ == "__main__": sc = SparkContext(appName="PythonSQL")
sqlContext = SQLContext(sc) # RDD is created from a list of rows
some_rdd = sc.parallelize([Row(name="John", age=19),
Row(name="Smith", age=23),
Row(name="Sarah", age=18)])
# Infer schema from the first row, create a DataFrame and print the schema
some_df = sqlContext.createDataFrame(some_rdd)
some_df.printSchema() # Another RDD is created from a list of tuples
another_rdd = sc.parallelize([("John", 19), ("Smith", 23), ("Sarah", 18)])
# Schema with two fields - person_name and person_age
schema = StructType([StructField("person_name", StringType(), False),
StructField("person_age", IntegerType(), False)])
# Create a DataFrame by applying the schema to the RDD and print the schema
another_df = sqlContext.createDataFrame(another_rdd, schema)
another_df.printSchema()
# root
# |-- age: integer (nullable = true)
# |-- name: string (nullable = true) # A JSON dataset is pointed to by path.
# The path can be either a single text file or a directory storing text files.
# if len(sys.argv) < 2:
# path = "file://" + \
# os.path.join(os.environ['SPARK_HOME'], "examples/src/main/resources/people.json")
# else:
# path = sys.argv[1]
path="D:\spark-1.6.0-bin-hadoop2.6\data\mllib\people.json";
# Create a DataFrame from the file(s) pointed to by path
people = sqlContext.jsonFile(path)
# root
# |-- person_name: string (nullable = false)
# |-- person_age: integer (nullable = false) # The inferred schema can be visualized using the printSchema() method.
people.printSchema()
# root
# |-- age: IntegerType
# |-- name: StringType # Register this DataFrame as a table.
people.registerAsTable("people") # SQL statements can be run by using the sql methods provided by sqlContext
teenagers = sqlContext.sql("SELECT name FROM people WHERE age >= 13 AND age <= 19") for each in teenagers.collect():
print(each[0])
# teenagers.append("namesAndAges.parquet", "parquet");
import json #teenagers.save("D:\spark-1.6.0-bin-hadoop2.6\data\mllib\peoplenew.json","json","append")
file_object = open("D:\spark-1.6.0-bin-hadoop2.6\data\mllib\peoplenew.json", 'w')
file_object.write("{'name':'222'}")
file_object.close() #teenagers.rdd.repartition(1).saveAsTextFile("D:\spark-1.6.0-bin-hadoop2.6\data\mllib\peoplenew1.json")
#sc.parallelize(teenagers.collect()).saveAsTextFile("D:\spark-1.6.0-bin-hadoop2.6\data\mllib\peoplenew1.json")
#sc.parallelize(teenagers.collect()).saveAsTextFile("D:\spark-1.6.0-bin-hadoop2.6\data\mllib\peoplenew1.json")
#error teenagers.rdd.repartition(1).saveAsTextFile("D:\spark-1.6.0-bin-hadoop2.6\data\mllib\peoplenew1.json"); import pymysql conn = pymysql.connect(host='aliyun.ovalcn.com', port=3306, user='root', passwd='oval163', db='pos_wanli_combine', charset='UTF8')
cur = conn.cursor()
cur.execute("SELECT * FROM biz_dms_order limit 2")
results = cur.fetchall()
orders = []
data = {}
# for i in range(len(cur.description)):
# print("Column {}:".format(i + 1))
# desc = cur.description[i]
# print(" column_name = {}".format(desc[0])) for row in results: orderDict = {}
for i in range(len(cur.description)):
# print("Column {}:".format(i + 1))
desc = cur.description[i]
#print(" column_name = {}".format(desc[0]))
colName = desc[0]
orderDict.setdefault(colName, str(row[i]))
#print(row[i])
# order[desc[0]] = row[i]
#setattr(orderDict,colName, row[i]) #print(row[i])
#orderDict['id'] =11
#print(row)
#orderDict.setdefault('id', 11) #i=0
orders.append(orderDict)
#print(json.dumps(orders))
data['code'] = 0
data['orders'] = orders
jsonStr = json.dumps(data)
print(jsonStr)
#print(data)
# for r in cur:
# print("row_number:" + str(cur.rownumber))
#print("id:" + str(r[0]) + "key:" + str(r[1]) + " mean:" + str(r[2])) # cur.close() conn.close() sc.stop()
python访问mysql将返回的表转化为json的更多相关文章
- Python访问MySQL(1):初步使用PyMySQL包
Windows 10家庭中文版,MySQL 5.7.20 for Win 64,Python 3.6.4,PyMySQL 0.8.1,2018-05-08 ---- 使用Python访问MySQL数据 ...
- Python查询Mysql时返回字典结构的代码
Python查询Mysql时返回字典结构的代码 MySQLdb默认查询结果都是返回tuple,输出时候不是很方便,必须按照0,1这样读取,无意中在网上找到简单的修改方法,就是传递一个cursors.D ...
- python访问mysql和redis
1. 修改mysql配置文件 修改bind-address=0.0.0.0(允许通过远程网络连接) 2. 修改redis配置文件 修改bind-address=0.0.0.0(允许通过远程网络连接), ...
- python查询mysql并生成excel表
需求说明 开发不愿意单独为某个项目做后台 并且运营那边需要合并多个表的数据 因此找上了我. 要求每周执行一次.月初也执行一次 要查询2个mysql数据库多个表并生成excel表 我的想法 找开发要sq ...
- 利用Python访问Mysql数据库
首先要明确一点,我们在Python中需要通过第三方库才能访问Mysql. 有这样几种方式:Mysql-python(即MySQLdb).pymysql.mysql-connector.Mysql-py ...
- Python访问MySQL数据库并实现其增删改查功能
概述:对于访问MySQL数据库的操作,我想大家也都有一些了解.不过,因为最近在学习Python,以下就用Python来实现它.其中包括创建数据库和数据表.插入记录.删除记录.修改记录数据.查询数据.删 ...
- python访问mysql
1,下载mysql-connector-python-2.0.4 pythoin访问mysql需要有客户端,这个就是连接mysql的库 解压后如下图: 双击lib 以windows为例 把mysql ...
- python 调用mysql存储过程返回结果集
存储过程: delimiter | ),)) begin select * from tb_test where mid = imid and user = iuser; end; | delimit ...
- python、mysql四-2:多表查询
一 介绍 本节主题 多表连接查询 复合条件连接查询 子查询 准备表 #建表 create table department( id int, name varchar() ); create tabl ...
随机推荐
- Java基础(1):Switch语句注意的5个地方
不得不说的几点小秘密: 1. switch 后面小括号中表达式的值必须是整型或字符型 2. case 后面的值可以是常量数值,如 1.2:也可以是一个常量表达式,如 2+2 :但不能是变量或带有变量的 ...
- 变形--位移 translate()
translate()函数可以将元素向指定的方向移动,类似于position中的relative.或以简单的理解为,使用translate()函数,可以把元素从原来的位置移动,而不影响在X.Y轴上的任 ...
- oracle中的常用语句
1:查看当前用户的缺省表空间 SELECT USERNAME, DEFAULT_TABLESPACE FROM USER_USERS; 2:查看当前用户的角色 SELECT * FROM USER_R ...
- 动态时间规整(DTW) 转载
Dynamic Time Warping(DTW)诞生有一定的历史了(日本学者Itakura提出),它出现的目的也比较单纯,是一种衡量两个长度不同的时间序列的相似度的方法.应用也比较广,主要是在模板匹 ...
- PAT乙级 1015. 德才论 (25)
1015. 德才论 (25) 时间限制 200 ms 内存限制 65536 kB 代码长度限制 8000 B 判题程序 Standard 作者 CHEN, Li 宋代史学家司马光在<资治通鉴&g ...
- 由ccf第一题引出的问题
当时的情况是这样的,代码中需要用到一个较大的二维数组,但只要定义这个大二维数组编译就出错,无奈后来用malloc自己实现了类似二维数组的操作. 其中的b数组设为全局的或者静态的也都可以解决overfl ...
- 【pyQuery分析实例】分析体育网冠军联盟比赛成绩
目标地址:http://www.espncricinfo.com/champions-league-twenty20-2012/engine/match/574265.html liz@nb-liz: ...
- C++代码段六
摘自<Primer Plus>浮点数优缺点: void test109() { float a=2.34E+22f; float b=a+1.0f; cout<<"a ...
- Report launcher to run SSRS report subscriptions on demand
http://www.mssqltips.com/sqlservertip/3078/report-launcher-to-run-ssrs-report-subscriptions-on-deman ...
- Fury观后感
刚看完,淋雨汽车回来的,电影很精彩.前期略慢热(我还去了躺厕所),军人的黑色幽默,冷酷的军旅生活作为基调.内容我就不ao述了,新兵蛋诺曼的经历是这部电影的为主线(也有人说诺曼是观众的代入点,准确来说他 ...