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 ...
随机推荐
- override与final
override 强调该函数是重写的父类的函数 final 指定该函数不能被重写 两者都是针对virtual 函数
- Spring 中的 Bean 配置
内容提要 •IOC & DI 概述 •配置 bean –配置形式:基于 XML 文件的方式:基于注解的方式 –Bean 的配置方式:通过全类名(反射).通过工厂方法(静态工厂方法 & ...
- 杭电oj 1016 Prime Ring Problem
Prime Ring Problem Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Other ...
- JQ 动态加载多选框--随记
=====================html <table> <tr> <td style="Width: 100px; text-align: righ ...
- rails控制台进入
数据库控制台: rails db .help查看可使用的命令 rails控制台 rails c 普通ruby控制台: irb
- logging
#coding=utf8 import sys, logging logging.basicConfig(level=logging.INFO, forma ...
- MYSQL日期类型的加减更新使用INTERVAL 1 DAY
例如:UPDATE teachingplan SET teachPlanBeginTime = teachPlanBeginTime +INTERVAL 1 DAY
- zw版【转发·台湾nvp系列Delphi例程】HALCON DispCross
zw版[转发·台湾nvp系列Delphi例程]HALCON DispCross procedure TForm1.Button1Click(Sender: TObject);var r, c : Ol ...
- SqlServer nvarchar中的中文字符匹配,更改SqlServer实例和数据库排序规则的办法
我们都知道在SqlServer中的nvarchar类型可以完美的存储诸如中文这种unicode字符,但是我们会发现有时候查询语句去查询nvarchar列的时候查不出来. 为什么nvarchar类型有时 ...
- UISlider控件属性及方法(转)
初始化一个Slider UISlider *slider = [[UISlider alloc]initWithFrame:CGRectMake(0, 400,320 , 20)]; 访问UI ...