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 ...
随机推荐
- String.Format数字格式化参考
String.Format数字格式化输出 {0:N2} {0:D2} {0:C2} (转) 数字 {0:N2} 12.36 数字 {0:N0} 13 货币 {0:c2} $12.36 货币 {0:c4 ...
- PHP XDEBUG
PHP调试时,不得不提XDEBUG这个调试利器.学习PHP以来,几乎所有的问题我都利用它来解决. 首先关于如何安装,不在赘述,请自行google之.(需要特别注意的是:PHP5.2 和5.3 ,关于加 ...
- 解决xfce4桌面图标消失的问题
问题表现:panel还在,桌面的背景变成灰色,桌面图标消失,桌面右键没反映 解决方法:从登录管理器中登录另一个用户,发现桌面正常,猜测是由于家目录下的配置文件引起的. 删除 ~/.cache/sess ...
- RobotFrameWork接口报文测试-----(三)demo的加强版(数据驱动测试)
在上一篇RobotFrameWork接口报文测试-----(二)demo的升级版基础上,将接口的xml的格式保存在xml文件中,然后程序如果增加一个接口,在xml文件里添加即可,无需修改自动化测试里的 ...
- php常见细节错误
PHP编程中10个最常见的错误 PHP是一种非常流行的开源服务器端脚本语言,你在万维网看到的大多数网站都是使用php开发的.本篇经将为大家介绍PHP开发中10个最常见的问题,希望能够对朋友有所帮助. ...
- 重要的事情说三遍:列表 ul / ol 等是块级元素,是块级元素,块级元素
HTML 块级元素 大多数 HTML 元素被定义为块级元素或内联元素. 编者注:“块级元素”译为 block level element,“行内元素”译为 inline element. 块级元素在浏 ...
- html5 图片热点area,map的用法
今天看了一个html5在图片上面创建热点的标签,所谓图片热点就是给你一张图片然后你可以设置点击图片不同的位置进入不同的链接!如果下面是一张图片的话,里面在长方形.圆形.三角形区域都可以进入其他网页! ...
- LUA之面向对象
Account = { balance=0, withdraw = function (self, v) self.balance = self.balance - v end } function ...
- webpack笔记_(2)_Refusing to install webpack as a dependency of itself
安装webpack时,出现以下问题: Refusing to install webpack as a dependency of itself npm ERR! Windows_NT npm ERR ...
- android 中activity调用远程service中的方法之 aidl的使用
服务端:只有服务,没有界面 1.编写interface文件,复制到 .aidl 文件中,并去掉其中的public 等修饰符.系统会自动在gen目录下生成对应的java文件 (对应本地调用中的接口文件 ...