#
# 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的更多相关文章

  1. 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数据 ...

  2. Python查询Mysql时返回字典结构的代码

    Python查询Mysql时返回字典结构的代码 MySQLdb默认查询结果都是返回tuple,输出时候不是很方便,必须按照0,1这样读取,无意中在网上找到简单的修改方法,就是传递一个cursors.D ...

  3. python访问mysql和redis

    1. 修改mysql配置文件 修改bind-address=0.0.0.0(允许通过远程网络连接) 2. 修改redis配置文件 修改bind-address=0.0.0.0(允许通过远程网络连接), ...

  4. python查询mysql并生成excel表

    需求说明 开发不愿意单独为某个项目做后台 并且运营那边需要合并多个表的数据 因此找上了我. 要求每周执行一次.月初也执行一次 要查询2个mysql数据库多个表并生成excel表 我的想法 找开发要sq ...

  5. 利用Python访问Mysql数据库

    首先要明确一点,我们在Python中需要通过第三方库才能访问Mysql. 有这样几种方式:Mysql-python(即MySQLdb).pymysql.mysql-connector.Mysql-py ...

  6. Python访问MySQL数据库并实现其增删改查功能

    概述:对于访问MySQL数据库的操作,我想大家也都有一些了解.不过,因为最近在学习Python,以下就用Python来实现它.其中包括创建数据库和数据表.插入记录.删除记录.修改记录数据.查询数据.删 ...

  7. python访问mysql

    1,下载mysql-connector-python-2.0.4  pythoin访问mysql需要有客户端,这个就是连接mysql的库 解压后如下图: 双击lib 以windows为例 把mysql ...

  8. python 调用mysql存储过程返回结果集

    存储过程: delimiter | ),)) begin select * from tb_test where mid = imid and user = iuser; end; | delimit ...

  9. python、mysql四-2:多表查询

    一 介绍 本节主题 多表连接查询 复合条件连接查询 子查询 准备表 #建表 create table department( id int, name varchar() ); create tabl ...

随机推荐

  1. 利用最新版的RubyMine2016.2开发Ruby On Rails 程序

    经过我的前两篇博文 ”Ruby On Rails环境搭建“ 和”Ruby On Rails 环境搭建MySQL数据库连接“ 我们已经具备了开发Ruby On Rails程序的一切要素,但是天天对着do ...

  2. extjs grid 单元格 多选

    new Ext.grid.CellSelectionModel({ last : false, // 上一次选中的单元格 selections : [], // 选择区缓存 handleMouseDo ...

  3. MSSQL 判断实例中是否存在某种表

    执行语句 SELECT 'SELECT * FROM '+Name+'..SysObjects Where XType=''U'' and name=''tab_scartrim'' ORDER BY ...

  4. ASP.NET MVC (一)

    工作清闲好一段时间了,趁这段时间弄了弄PHP,做个了简单的MVC网页.玩了玩Android,弄了个拨号器,发短信的,嘿嘿,最满意的还是两天弄了个数独游戏.不务正业一个多月了,也该磨磨刀,接下来一段时间 ...

  5. 将服务费用DIY到底----走出软件作坊:三五个人十来条枪 如何成为开发正规军(十)[转]

    前一段时间,讲了一系列开发经理.实施经理.服务经理的工具箱:开发经理的工具箱---走出软件作坊:三五个人十来条枪 如何成为开发正规军(三) ,实施经理的工具箱--走出软件作坊:三五个人十来条枪 如何成 ...

  6. Asp.Net MVC 模型验证详解-实现客户端、服务端双重验证

    概要 在asp.net webform开发中经常会对用户提交输入的信息进行校验,一般为了安全起见大家都会在客户端进行Javascript(利于交互).服务端双重校验(安全).书写校验代码是一个繁琐的过 ...

  7. 请求在Struts2框架中的处理步骤

    上图来源于Struts2官方站点,是Struts 2 的整体结构. 一个请求在Struts2框架中的处理大概分为以下几个步骤 1 客户端初始化一个指向Servlet容器(例如Tomcat)的请求 2 ...

  8. iOS证书申请详细流程

    一.事前准备 1.1 准备苹果帐号 首先您需要有一个苹果的开发者帐号,一个mac系统.如果没有帐号可以打开申请加入苹果的开发者计划.如何申请网上有详细的介绍,在此不多做介绍. 如果您已经有了一个帐号, ...

  9. Android NDK 开发(二) -- 从Hlello World学起【转】

    转载请注明出处:http://blog.csdn.net/allen315410/article/details/41805719  上篇文章讲述了Android NDK开发的一些基本概念,以及NDK ...

  10. 161130、Dubbo+SpringMVC工程创建详解

    Dubbo出现的目的是为了应对现在高并发,高数据量请求的问题.目前的垂直应用架构已经无法满足现在大数据的冲击,SOA就应运而生,而Dubbo在国内使用的还是比较多,稳定性也比较不错. 架构 节点角色说 ...