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 ...
随机推荐
- CCF真题之日期计算
201509-2 日期计算 问题描述 给定一个年份y和一个整数d,问这一年的第d天是几月几日? 注意闰年的2月有29天.满足下面条件之一的是闰年: 1) 年份是4的整数倍,而且不是100的整数倍: 2 ...
- PTPX中的clock tree与LP design
PTPX在加入CPF/UPF这样的文件后,可以分析multi-voltage,power-gating这样的设计. 针对某个power rail的cell,PTPX支持进行annotate. set_ ...
- 机器学习中的范数规则化之(一)L0、L1与L2范数(转)
http://blog.csdn.net/zouxy09/article/details/24971995 机器学习中的范数规则化之(一)L0.L1与L2范数 zouxy09@qq.com http: ...
- 5. 星际争霸之php设计模式--抽象工厂模式
题记==============================================================================本php设计模式专辑来源于博客(jymo ...
- 形状特征提取-Hu不变矩(转载)
[原文部分转载]:http://blog.csdn.net/wrj19860202/archive/2011/04/16/6327094.aspx 在连续情况下,图像函数为 ,那么图像的p+q阶几何矩 ...
- hibernate笔记03
- Openstack的删除错误网桥,虚拟网络
在实验openstack的各种网络模式时,可能会产生一些错误的网络指向,需要删除那些网桥. 执行前 [root@node-9 ~]# ifconfig br40 Link encap:Ethernet ...
- 在CentOS 6 32/64 上安装 PPTP 方式 VPN 服务
网上有很多步骤, 讲了很多步骤,废话, 其实不如直接看代码, 而且也能直接运行,快速安装: rm -f /etc/pptpd.conf rm -f /etc/ppp arch=`uname -m` # ...
- ubuntu apache开启重写模块
http://www.iblue.cc/2011/09/ubuntu-apache%E5%BC%80%E5%90%AF%E9%87%8D%E5%86%99%E6%A8%A1%E5%9D%97/ Ubu ...
- Linux内核抢占与中断返回【转】
转自:http://blog.csdn.net/tommy_wxie/article/details/7425728 版权声明:本文为博主原创文章,未经博主允许不得转载. [html] view pl ...