에러 상황1)

sqoop export --connect.. --table mysql 타겟 테이블 --export-dir hdfs://nameservice1... 시 

export dir hive 테이블이 ORC 테이블이여서.. export 에러가 났다.

 

관련 개념)

Hive 테이블 생성 종류

CREATE TABLE IF NOT EXISTS 테이블명 (

..

)

PARTITIONED BY (column_name datatype)

ROW FORMAT DELIMITED

FIELDS TERMINATED BY '\001'

LINES TERMINATED BY '\n'

 

1) 로우 포맷, ROW FORMAT DELIMITED

- 행과 특정 행의 필드가 저장된 방식을 지시한다.

- 기본 행 문자는 아스키 제어 코드의 ctrl A (^A) 문자다.

- FIELDS TERMINATED BY '\001'는 하이브가 필드 구분자를 ^A character로 사용하겠다는 것.

- LINES TERMINATED BY '\n'는 라인을 \n (아스키 코드)로 구분하겠다는 것.

 

2) 바이너리 저장 포맷, STORED AS ORC

바이너리 포맷은 행의 형식이 특정 바이너리 포맷에 따라 결정되므로 ROW FORMAT을 지정하지 않아도 된다.

CREATE TABLE IF NOT EXISTS 테이블명 (

..

)

PARTITIONED BY (column_name datatype)

STORED AS ORC

TBLPROBERTIES ('ORC.COMPRESS' = 'SNAPPY')

- The TBLPROPERTIES clause allows you to tag the table definition with your own metadata key/value pairs

- SNAPPY는 codec이다. snappy is fast data compression and decompression library written in C++.......

 

에러 상황2)

sqoop export --connect.. --table mysql 타겟 테이블 --export-dir hdfs://nameservice1... 시 

export-dir인 hive 경로 테이블 컬럼에 null값이 있는 경우 sqoop이 되지 않고 에러가 발생한다.

 

에러 확인:

hadoop application 로그를 보면,,

Caused by: java.lang.RuntimeException: Can't parse input data: '\n'로 에러 로그를 확인할 수 있다.

 

해결 방법:

export 출처 hive 디렉토리 테이블에서 어떤 필드가 null값을 가지는지 확인하고 쿼리에서 제외처리해준다.

 

더나아가서..

무조건 null값은 제외해주는게 맞는 방법인가싶다.

시스템에서 수집되는 값이 널이거나, 중간에 전처리 과정에서 조인이 되지 않아 null인 경우도 있는데

근본적으로 데이터가 제대로 들어오지 않은 원인을 찾는게 중요할 것같다.

 

'Hadoop > 수집: Sqoop' 카테고리의 다른 글

sqoop error fixed: Directory could not be cleaned up  (0) 2022.01.05

필요한 개념

1) Map join

특정 테이블의 데이터가 메모리에 모두 들어갈 수 있을 정도의 크기이면

(설정: hive.mapjoin.bucket.cache.size)

하이브는 각 매퍼에서 조인을 수행할 수 있도록 모든 데이터를 메모리에 로드한다.

 

이 쿼리 실행 잡은 레듀서가 필요없다. 

right join, full outer join에서는 제대로 작동하지 않는다.

일치의 부재는 전체 입력을 대상으로 집계(리듀스)를 수행하는 과정에서만 탐지할 수 있기 때문이다..

-> 결국 버킷 테이블/아닌테이블이 맵조인을 수행했을 때 이 쿼리의 집계결과에서 데이터 불일치가 발견되는 것은

집계 (리듀스) 수행과정에서만 탐지할 수 있기 때문이군..

 

왼쪽 테이블의 버킷을 처리하는 맵퍼는 조인을 수행할 때 테이블의 관련 버킷만 불러오면 된다. 

 

맵 조인을 사용하려면 다음과 같이 최적화 설정을 활성화 해두어야한다.

set hive.optimize.bucketmapjoin = true;

 

2) Bucket

테이블을 버킷으로 구조화하는 이유

-효율적인 쿼리가 가능하다. 버킷팅은 테이블에 대한 추가 구조를 부여하여 버킷된 테이블 끼리 맵조인 수행시 효율적이다.

-효율적인 샘플링에 유리하다.

 

CREATE TABLE bucketed_users (id int, name string)

CLUSTERED BY (id) INTO 4 BUCKETS;

 

하이브는 아이디를 해싱하고 그 값을 버킷수 4개로 나눈 나머지를 버킷의 번호로 선택.

 

3) 설정값 

ambari > hive > configs >advanced

 

hive.auto.convert.join = False

hive.auto.convert.join.noconditionaltask = true

hive.optimize.bucketmapjoin.sortedmerge = False

hive.auto.convert.join.noconditionaltask.size = 

 

hive.convert.join.bucket.mapjoin.tez = False

hive.mapjoin.bucket.cache.size = 10000

hive.optimize.bucketmapjoin = true

hive.enforce.sortmergebucketmapjoin = true

hive.optimize.bucketmapjoin.sortedmerge = False

 

데이터 누락 확인 상황

-Bucket 테이블과 Bucket 아닌 테이블간의 조인시 조인이 제대로 되지 않음.

-select * bucket table join unbucket table on id 로 조인을 시도하면,

조인 결과 count(*)시 아래 모두 개수는 동일함.

버킷 테이블, 버킷 아닌 테이블 mapjoin한 결과 - case1

버킷 아닌 테이블, 버킷 아닌 테이블 map join한 결과 - case2

버킷 테이블, 버킷 테이블  map join한 결과 - case3

-하지만 버킷 테이블을 생성할 때 clustered by (column) 으로 지정한 조인 컬럼에 특정 값으로 조회를 하면 join한 전체 결과 count(*), select * 해보면 case2,3에서는 조회되지만 case1에서는 조회되지 않음

 

 

결국에 버킷 테이블은 버킷 테이블끼리 map join을 해야지 clustered by 된 컬럼을 기준으로 조인 결과 조회가 정상적으로 되는 것같다.

 

 

 

 

'Hadoop > 처리: Hive SQL' 카테고리의 다른 글

view, index  (0) 2021.07.04

Before we start..

1) shortcoming of Mapreduce,

- Read from disk for each MapReduce job.

- Only native Java programming interface. 

2) so here we have Spark!

- Same features of Mapreduce and more.

- Capable of reusing Hadoop ecosystem like HDFS, YARN..

- lot more easier to build data analysis pipeline.

- In-memory caching of data, specified by the user

- 스파크는 실행 엔진으로 맵리듀스를 사용하지 않고, 클러스터 기반으로 작업을 실행하는 자체 분산 런타임 엔진이 있다.

- 매번 디스크에서 데이터 셋을 읽는 맵리듀스 워크플로우에 비해 10배 혹은 더 빠른 성능.

- DAG엔진을 제공하여 연산자 중심의 파이프라인을 처리해서 사용자를 위한 단일 잡으로 변환한다.

- MLlib, GraphX, Spark Streaming, Spark SQL 모듈은 아파치 프로젝트에 포함된다.

3) Architecture of Spark

- Worker Node: 

Spark Executor Java VM <-> interface to HDFS

- Spark assign mapping stage, having data read from HDFS process in memory, results stored as one RDD.

- If running pyspark, data goes to python from the java vm for processing.

- Cluster Manager: Yarn/Standalone Provision/Restart Workers.

-> Standalone for restarts node when the other node is dead.

 

- Driver Program: Spark context. this is the interface to cluster manager <-> worker nodes.

SC is object which defines how Spark is access to the cluster.

- Context is the 'gateway' for us to connect to our spark instance and submit jobs.

- Submit jobs mean execute command on the shell.

- spark context with the variable 'sc' to read data into spark.

Architecture of Spark

4) RDD(Resilient Distributed Datasets)

- 'the way' in spark to store my data.

- 클러스터에 있는 다수의 머신에 분할되어 저장된 읽기 전용 컬렉션.

- 스파크 프로그램은 하나 혹은 그 이상의 RDD를 입력받고 일련의 변환 작업을 거쳐 목표 RDD 집합으로 변형된다.

- 이 과정에서 결과를 계산하거나 영구 장소에 저장하는 '액션' 이 수행된다.

- RDD로 데이터를 로드하거나 transformation 변형 연산을 수행해도 실제로 데이터는 '처리'되지 않는다. 계산을 위한 수행  '계획'이 만들어진다. 실제 계산은 액션을 호출할 때 수행된다.

- RDDs are created by starting with a file in the Hadoop file

 

RDD를 만드는 3가지 방법

1) 객체의 인메모리 컬렉션으로 생성

val params = sc.parallelize(1 to 10)

val result = params.map(performExpensizeComputation) 이 함수는 입력값을 병렬로 실행한다. 병렬 처리의 수준은 spark.default.parallelism 속성으로 결정되고, 기본값은 스파크 잡 실행 위치에 따라 달라진다(?)

로컬에서 실행하면 컴퓨터의 코어수, 클러스터에서 수행하면 클러스터의 모든 executor의 토털 core 수에 따라 달라진다.

 

ex)

integer_RDD = sc.parallelize(range(10),3) 

3 numbers of partition and sc.parallelize: function gives you back a reference to your RDD.

 

2) HDFS와 같은 기존 외부 저장소의 데이터셋을 사용

val text: RDD[string] = sc.textFile(inputPath)

hdfs의 경우 1 hdfs block, 1 spark partition이다.

 

3) 기존의 RDD를 변환

스파크는 RDD에 트랜스포메이션, 액션이라는 두 종류의 연산자를 제공한다.

트랜스포메이션은 기존 RDD에서 새로운 RDD를 생성한다.

반면 액션은 특정 RDD를 계산하여 어떤 결과를 만들어낸다.

스파크는 lazy 해서 트랜스포메이션이 적용된 RDD에 액션이 수행될때까지는 아무런 동작을 하지 않는다.

- Dataset is like a variable/object in programming.

- Data storage is created from HDFS, HBase, Json..

-> HDFS Hive

- 'Distributed' across the cluster of machines.

- Data are divided in partitions. Spark does not process data by line but as a chunks.

 

- Partitions -> machines.

- Resilient (not failing). Recover from errors node failure, slow processes.

- 유실된 파티션이 있을 때 스파크가 RDD의 처리 과정을 다시 계산하여 자동으로 복구할 수 있다.

- Discover where to start on failed partition.

 

ex)

integer_RDD.glom().collect()

glom(): to check how the data are partitioned across the cluster of nodes. 

collect(): Spark collect() and collectAsList() are action operation that is used to retrieve all the elements of the RDD/DataFrame/Dataset (from all nodes) to the driver node

 

- read text into spark

text_RDD = sc.textFile('/usr/hmc/input/testfile1')

 

- wordcount example

function1)

def split_words(line):

    return line.split()

 

words_RDD = text_RDD.flatMap(split_words)

words_RDD.collect()

flatMap: apply function to each of the element of our RDD.

 

output[]: [u'A', u'long', u'time', u'ago', u'in', u'a', u'galaxy', u'far', u'far', u'away']

 

function2)

def create_pair(word):

    return (word,1)

 

pairs_RDD=text_RDD.flatMap(split_words).map(create_pair)

pairs_RDD.collect()

output: [('word',numofword),...] output is key value pair!

Out[]: [(u'A', 1), (u'long', 1), (u'time', 1), (u'ago', 1), (u'in', 1), (u'a', 1), (u'galaxy', 1)

 

pairs_RDD.groupByKey().collect()

for k,v in pairs_RDD.groupByKey().collect(): print "Key:", k, ",Values:", list(v)

Out[]: Key: A , Values: [1] Key: ago , Values: [1] Key: far , Values: [1, 1] Key: away , Values: [1] Key: in , Values: [1] Key: long , Values: [1] Key: a , Values: [1]

5) Spark Transformations

-RDD are immutable (no transactional)

-Never modify RDD in place.

-Transform RDD to another RDD to final result (by reducer)

 

-Create RDD

1)map: apply function to each element of RDD

함수를 적용하는 것으므로 이 트랜스포메이션 자체로는 아무런 동작을 하지 않는다! 수행 계획을 세울뿐..

 

def lower(line):

      return line.lower()

lower_text_RDD = text_RDD.map(lower)

 

partitions are chunks of our data.

Partitions -> Map() -> Partitions (between same size of partitions)

 

-flatMap

def split_words(line):

      return line.split()

 

words_RDD = text_RDD

flatMap(split_words)

words_RDD.collect()

 

-Transformations

map(func) Return a new distributed dataset formed by passing each element of the source through a function func.
filter(func) Return a new dataset formed by selecting those elements of the source on which func returns true.
flatMap(func) Similar to map, but each input item can be mapped to 0 or more output items (so func should return a Seq rather than a single item).
mapPartitions(func) Similar to map, but runs separately on each partition (block) of the RDD, so func must be of type Iterator<T> => Iterator<U> when running on an RDD of type T.
mapPartitionsWithIndex(func) Similar to mapPartitions, but also provides func with an integer value representing the index of the partition, so func must be of type (Int, Iterator<T>) => Iterator<U> when running on an RDD of type T.
sample(withReplacement, fraction, seed) Sample a fraction fraction of the data, with or without replacement, using a given random number generator seed.
union(otherDataset) Return a new dataset that contains the union of the elements in the source dataset and the argument.
intersection(otherDataset) Return a new RDD that contains the intersection of elements in the source dataset and the argument.
distinct([numPartitions])) Return a new dataset that contains the distinct elements of the source dataset.
groupByKey([numPartitions]) 가장 많이 사용하는 메서드로, 값을 집계하려면 셔플을 해야한다.

When called on a dataset of (K, V) pairs, returns a dataset of (K, Iterable<V>) pairs.
Note: If you are grouping in order to perform an aggregation (such as a sum or average) over each key, using reduceByKey or aggregateByKey will yield much better performance.
Note: By default, the level of parallelism in the output depends on the number of partitions of the parent RDD. You can pass an optional numPartitions argument to set a different number of tasks.

pairs_RDD.groupByKey().collect()


"shuffle" through the different nodes while groupbykey works.
reduceByKey(func, [numPartitions]) 하나의 값이 나올때까지 반복적으로 키-값 쌍의 값에 이진 함수를 적용.
이 메서드는 스칼라 tuple2로 정의된 key-value 쌍의 RDD만 가능하다.
그러므로 이 연산을 수행하기 전에 RDD를 map() 메서드를 이용해서 먼저 키-벨류로 변환해줘야한다.
When called on a dataset of (K, V) pairs, returns a dataset of (K, V) pairs where the values for each key are aggregated using the given reduce function func, which must be of type (V,V) => V. Like in groupByKey, the number of reduce tasks is configurable through an optional second argument.
aggregateByKey(zeroValue)(seqOp, combOp, [numPartitions]) When called on a dataset of (K, V) pairs, returns a dataset of (K, U) pairs where the values for each key are aggregated using the given combine functions and a neutral "zero" value. Allows an aggregated value type that is different than the input value type, while avoiding unnecessary allocations. Like in groupByKey, the number of reduce tasks is configurable through an optional second argument.
sortByKey([ascending], [numPartitions]) When called on a dataset of (K, V) pairs where K implements Ordered, returns a dataset of (K, V) pairs sorted by keys in ascending or descending order, as specified in the boolean ascending argument.
join(otherDataset, [numPartitions]) When called on datasets of type (K, V) and (K, W), returns a dataset of (K, (V, W)) pairs with all pairs of elements for each key. Outer joins are supported through leftOuterJoin, rightOuterJoin, and fullOuterJoin.
cogroup(otherDataset, [numPartitions]) When called on datasets of type (K, V) and (K, W), returns a dataset of (K, (Iterable<V>, Iterable<W>)) tuples. This operation is also called groupWith.
cartesian(otherDataset) When called on datasets of types T and U, returns a dataset of (T, U) pairs (all pairs of elements).
pipe(command, [envVars]) Pipe each partition of the RDD through a shell command, e.g. a Perl or bash script. RDD elements are written to the process's stdin and lines output to its stdout are returned as an RDD of strings.
coalesce(numPartitions) Decrease the number of partitions in the RDD to numPartitions.
Useful for running operations more efficiently after filtering down a large dataset.


ex) sc.parallelize(range(10),4).glom().collect()
out[]: [[0,1],[2,3],[4,5],[6,7,8,9]]

ex) sc.parallelize(range(10),4).coalesce(2).glom().collect()
out[]: [[0,1,2,3],[4,5,6,7,8,9]]

by glom().collect()
we can find our this data set was split in 4 partitions

repartition(numPartitions) Reshuffle the data in the RDD randomly to create either more or fewer partitions and balance it across them. This always shuffles all data over the network. ( even distributions of your cluster)
<-> Coaleace does locally
1) Try with coalesce.. if the local merging of partitions is good enough for my app
2) Use repartition 
repartitionAndSortWithinPartitions(partitioner) Repartition the RDD according to the given partitioner and, within each resulting partition, sort records by their keys. This is more efficient than calling repartition and then sorting within each partition because it can push the sorting down into the shuffle machinery.

reference: https://spark.apache.org/docs/latest/rdd-programming-guide.html#overview

 

-groupByKey + reduce vs reduceByKey

reduceByKey:

improve this by doing first sum before transfer through the network.

 

-saveAsTextFile() 메서드는 스파크 잡을 즉시 실행한다. 반환값이 없어도 RDD를 계산하여 결과 파티션을 output directory에 파일로 기록한다.

 

 

 

 

 

 

'Hadoop' 카테고리의 다른 글

하둡 스터디1.  (0) 2021.10.26
MySql DML  (0) 2017.02.27
python 데이터 - mysql 익숙해지기  (0) 2017.01.22
MySQL user 생성/권한주기 -> python연동  (0) 2017.01.22
MySQL 실행/기본  (0) 2017.01.22

에러상황

Sqoop시 root계정으로 실행, root 계정으로 실행하여 생성된 directory에 hive 계정으로 sqoop을 실행하면 아래 명령어에서 에러

 

수행 명령어

sqoop import --connect '..connection정보..' --username '..' --password '..'

--table mysqltablename -> 읽을 테이블

--delete-target-dir -> hdfs destination dir

--hive-import 

--hive-overwrite -> 해당 테이블 디렉토리에 존재하는 모든 테이블을 삭제하는 기능. overwrite이 생략되면 새로운 파일은 디렉토리에 추가된다.

--hive-database dbname

--hive-table tablename

--fields-terminated-by ',' -m 1 -> 파일 구분자를 ,로 & map task를 1로 지정

 

오류해결위해 알아야하는 개념

1) hadoop 접근 권한

- 파일을 수행한 권한이 root면 다른 권한으로 해당 디렉토리를 --delete-target-dir 할 수 없다.

- 따라서 su hdfs 계정으로 전환 후 아래 명령어로 생성된 디렉토리의 소유자를 변경해줘야한다.

- hadoop fs -chown -R hive(바꾸려는 owner):hdfs(바꾸려는 그룹명) /warehouse/tablespace..디렉토리명 

 

2) sqoop할때마다 delete target dir 수행 이유

- HDFS는 단일 라이터로 파일을 쓴다.

- 한 번 쓰고 끝나거나 파일의 끝에 덭붙이는 것은 가능하지만 파일에서 임의 위치에 있는 내용을 수정하는 것은 허용하지 않음

- 다중 라이터도 지원하지 않는다.

 

 

 

 

'Hadoop > 수집: Sqoop' 카테고리의 다른 글

sqoop error fixed: sqoop export시 Null값 있으면 에러  (0) 2022.01.24

2021/10/26

1주차: 하둡 스택 

- 스키마를 먼저 읽어오는 방식

- 프레임워크 

 1)Hive

 2)Hbase (Online NoSQL)

 3)Yarn (Manage resource manager)

: 클러스터를 효율적으로 관리

 4)Map reduce (scale data)

   -> Job tracker, Task Tracker로 구성

 5)HDFS 

   -> Namenode, datanode로 구성

 

자유노트:

- Hive를 실행하는 엔진은 Tez이다. MapReduce는 디폴트로 설정된 실행 엔진이고 이를 Tez가 대체한다.

- Hue 어플리케이션에서 Hive쿼리를 수행하면 수행 순서는 아래와 같다

1. Hive compile SQL

2. Tez가 쿼리를 execute

3. YARN이 리소스를 할당.

4. Hive updates the data in HDFS or the Hive warehouse

5. Hive returns query results over a JDBC connection

 

- Hue에서 데이터를 조회하기전, Hive에서는 메타데이터만 가지고 있음

- Hive는 mysql과 다르게 update, delete 수행을 할 수 없음. 대신에 drop partition으로 데이터를 날릴 수 있음.

- DROP TABLE external table을 하면, hive는 메타데이터(스키마)만 삭제하고 실제 데이터는 삭제하지 않음. 

- 실제로 hdfs에 데이터를 다 지우고 싶으면 

hadoop fs -rm -R -skipTrash /warehouse/tablespace/external/hive/db명/테이블명 으로 지운다.

- 그리고 나서 drop external table

 

+ 파일시스템에 파일데이터를 넣는 방법

1. sudo su -

2. mv fileexample.csv /home/hdfs

3. sudo su - hdfs

4. hdfs dfs -mkdir /user/example

5. hdfs dfs -chmod 777 /user/example

*chmod 777: readable, writable and executable by all users

 

6. hdfs dfs -put /home/hdfs/fileexample.csv /user/example

7. hdfs dfs -chmod 777 /user/example/fileexample.csv

- hdfs에 있는 데이터를 불러와서 external table schema로 만들어준다.

 

- 아래 명령어로 external table 을 managed table로 옮겨준다.

insert overwrite table (External table name)

 

Q. hive external table을 드롭하면 hdfs에서도 데이터가 지워질까?

drop external table을 하면, hdfs에 partition 디렉토리에 파일은 지워지지 않아 있다.

그래서 hadoop fs -rm -R -skipTrash /warehouse/tablespace/external/hive/db명/테이블명 으로 지운다. (위에 내용 참고)

 

- Sqoop

HDFS , RDB 사이에서 데이터를 전송해주는 툴 

Export: hive에서 생성된 테이블을 mysql로 옮겨준다.

그전에 mysql 에서 hive에서 export할 데이터를 담을 스키마를 생성해준다.

 

 

 

 

참고: https://docs.cloudera.com/HDPDocuments/HDP3/HDP-3.1.5/hive-overview/content/hive_whats_new_in_this_release_hive.html

 

What's new in this release: Apache Hive

HDP 3.x includes many Apache Hive 3 enhancements. HDP 3.x can help you improve query performance and comply with internet regulations. A few interfaces available in prior releases are unsupported in HDP 3.x. HDP 3.1.5 key features In HDP 3.1.5 and later, S

docs.cloudera.com

https://docs.cloudera.com/HDPDocuments/HDP3/HDP-3.1.5/using-hiveql/content/hive_create_an_external_table.html

 

Create, use, and drop an external table

You use an external table, which is a table that Hive does not manage, to import data from a file on a file system, into Hive. In contrast to the Hive managed table, an external table keeps its data outside the Hive metastore. Hive metastore stores only th

docs.cloudera.com

https://docs.cloudera.com/sqoop/1.4.7.7.1.6.0/user-guide/index.html#_literal_sqoop_export_literal

 

Sqoop User Guide (v1.4.7.7.1.6.0-297)

 

docs.cloudera.com

 

https://hadoop.apache.org/

 

Apache Hadoop

 

'Hadoop' 카테고리의 다른 글

Spark Concept 1)  (0) 2022.01.09
MySql DML  (0) 2017.02.27
python 데이터 - mysql 익숙해지기  (0) 2017.01.22
MySQL user 생성/권한주기 -> python연동  (0) 2017.01.22
MySQL 실행/기본  (0) 2017.01.22

1. 뷰 생성 장점?

- 디스크 메모리에 저장되지 않고, 제한된 접근으로 제한된 컬럼만 조회할 수 있다. (실수로 데이터가 지워지는 사고 방지)

 

2. 인덱스 생성

- partition은 hdfs 레벨에서 지원되고, 테이블 레벨에서는 인덱스가 지원된다.

- 인덱스는 컬럼에 생성해준다.

select * from table_name

create index index_name on table table_name(column_name) as 'compact' with defered rebuild;

 

 

'Hadoop > 처리: Hive SQL' 카테고리의 다른 글

Error fixed: Hive bucket table map join data loss  (0) 2022.01.13

0. 


1. My Sql 데이터베이스 생성


-> QuoteEye 서버 접속

-> 데이터베이스

-> Quote 테이블 접근

-> indexA, indexB 컬럼 추가

-> quote.py 에서 저장한 값 추가


2. quote.py 에서 저장한 값 indexA, indexB 값 전달 받기 -> SaveToDB.py 로



while True:
try:
s,e,v = findvalue(article_text3,'"',e,'"')

# v = STRING[indexA:indexB].strip() "인용구"

# print("indexA, indexB+len(bSub), quote: ")

print(s,e,v)

# 인용문 리스트에 추가
quotations.append(v)


except ValueError:
break


이 부분에서 s,e 값을 컬럼에 저장 할 수 있는 형태로 저장


Try 1. s,e 를 담을 튜플을 생성 , s , e 를 튜플에 저장



* 파이썬 자료 구조: 튜플 정리








SavedToDB.py 에서는 마지막 값만 출력이 된다. index_tuple





???????


일단 git에 푸시




'Hadoop' 카테고리의 다른 글

Spark Concept 1)  (0) 2022.01.09
하둡 스터디1.  (0) 2021.10.26
python 데이터 - mysql 익숙해지기  (0) 2017.01.22
MySQL user 생성/권한주기 -> python연동  (0) 2017.01.22
MySQL 실행/기본  (0) 2017.01.22

파이썬 (외부)에서 mysql에 접근하고 연동시키는 삽질을 드디어 끝냈다 !! (정답은 삽질이었다!)


이제 파이썬 웹 크롤러로 연합뉴스에 접근해 얻어온 데이터들 (컬럼: 후보자명, 기사제목, 내용, 링크, 날짜)룰 변수에 저장.


mysql에 데이터베이스를 생성, 테이블을 추가


컬럼에 변수들을 하나 하나 넣는 작업을 해보자 ^^!!


(위의 순서가 맞나 확인 받기)

'Hadoop' 카테고리의 다른 글

하둡 스터디1.  (0) 2021.10.26
MySql DML  (0) 2017.02.27
MySQL user 생성/권한주기 -> python연동  (0) 2017.01.22
MySQL 실행/기본  (0) 2017.01.22
JDBC  (0) 2017.01.21

pymysql로 mysql에 접근하려면 호스트에 접근 권한을 부여해줘야한다.


<순서>


- user 생성

create user '아이디'@'localhost' identified by '비밀번호';

localhost or % ( : 원격 접속가능)

 

- user 권한 부여

grant select, insert, update, delete, create, drop, alter on 지정DB이름.*to '아이디'@'localhost';

all privileges : 모든 권한 / *.* : 모든DB / with grant option : 권한위임가능


- user 권한 보기

show grants for '아이디'@'localhost(또는%)';

 

- 권한 적용

flush privileges;

 

 

- 모든 user 보기 , mysql DB의 user table

use mysql;

select user from user;


- user 삭제

drop user '아이디'@'접속영역(localhost or %)';

 

참고/출처: http://blog.naver.com/PostView.nhn?blogId=eagle823&logNo=90174385732



<MySQL root 사용자 계정>

http://withcoding.com/27


mysql설치,사용자 추가

mysql 외부접속권한


mysql 원격접속허용



'Hadoop' 카테고리의 다른 글

MySql DML  (0) 2017.02.27
python 데이터 - mysql 익숙해지기  (0) 2017.01.22
MySQL 실행/기본  (0) 2017.01.22
JDBC  (0) 2017.01.21
쿼트아이1) MySQL 익숙해지기.  (0) 2017.01.21


우선 내 PC에 MySQL이 저장되어있는 곳은 C:\mysql...tab키 \bin 디렉토리이다.


1. cmd 띄어 둔 후 


2. >> mysql -hlocalhost -uroot -p


3 >> password: kelly2017



**문제는 가끔 원격접속 시

ERROR 2003 (HY000): Can't connect to MySQL server on '.. 해당오류가 난다.


**해결방법>> 관리자 권한 cmd 실행 후 >> mysqld.exe -u root --skip-grant-tables 명령어 or mysqld.exe -uroot --skip-networking

              >>다시 관리자 원한 cmd 실행 후>> mysql hlocal -uroot -p 접속 ! 










<Opentutorial 참조>

데이터베이스 보기

1
show databases;

데이터베이스 생성

1
CREATE DATABASE opentutorials CHARACTER SET utf8 COLLATE utf8_general_ci;

데이터베이스 선택

1
use opentutorials;

테이블 생성

1
2
3
4
5
6
7
8
CREATE TABLE `topic` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`title` varchar(100) NOT NULL,
`description` text NOT NULL,
`author` varchar(30) NOT NULL,
`created` datetime NOT NULL,
PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

생성된 테이블 확인

1
show tables;

데이터 삽입

1
2
3
4
INSERT INTO `topic` (`id`, `title`, `description`, `author`, `created`) VALUES(1, 'About JavaScript', '<h3>Desctiption</h3>\r\n<p>JavaScript is a dynamic computer programming language. It is most commonly used as part of web browsers, whose implementations allow client-side scripts to interact with the user, control the browser, communicate asynchronously, and alter the document content that is displayed.</p>\r\n<p>\r\nDespite some naming, syntactic, and standard library similarities, JavaScript and Java are otherwise unrelated and have very different semantics. The syntax of JavaScript is actually derived from C, while the semantics and design are influenced by the Self and Scheme programming languages.\r\n</p>\r\n<h3>See Also</h3>\r\n<ul>\r\n <li><a href="http://en.wikipedia.org/wiki/Dynamic_HTML">Dynamic HTML and Ajax (programming)</a></li>\r\n <li><a href="http://en.wikipedia.org/wiki/Web_interoperability">Web interoperability</a></li>\r\n <li><a href="http://en.wikipedia.org/wiki/Web_accessibility">Web accessibility</a></li>\r\n</ul>\r\n', 'egoing', '2015-03-31 12:14:00');
INSERT INTO `topic` (`id`, `title`, `description`, `author`, `created`) VALUES(2, 'Variable and Constant', '<h3>Desciption</h3>\r\n\r\nIn computer programming, a variable or scalar is a storage location paired with an associated symbolic name (an identifier), which contains some known or unknown quantity or information referred to as a value. The variable name is the usual way to reference the stored value; this separation of name and content allows the name to be used independently of the exact information it represents. The identifier in computer source code can be bound to a value during run time, and the value of the variable may thus change during the course of program execution.\r\n\r\n<h3>See Also</h3>\r\n<ul>\r\n<li>Non-local variable</li>\r\n<li>Variable interpolation</li>\r\n</ul>\r\n', 'k8805', '2015-05-14 10:04:00');
INSERT INTO `topic` (`id`, `title`, `description`, `author`, `created`) VALUES(3, 'Opeartor', '<h2>Operator</h2>\r\n<h3>Description</h3>\r\n<p>Programming languages typically support a set of operators: constructs which behave generally like functions, but which differ syntactically or semantically from usual functions</p>\r\n<p>Common simple examples include arithmetic (addition with +, comparison with >) and logical operations (such as AND or &&). </p>\r\n', 'egoing', '2015-06-18 05:00:00');
INSERT INTO `topic` (`id`, `title`, `description`, `author`, `created`) VALUES(


이렇게 데이터를 생성한 후에 파이썬에서 접근해보려고 한다.


참고: 에러가 날때

http://oyeahhh.tistory.com/75

'Hadoop' 카테고리의 다른 글

MySql DML  (0) 2017.02.27
python 데이터 - mysql 익숙해지기  (0) 2017.01.22
MySQL user 생성/권한주기 -> python연동  (0) 2017.01.22
JDBC  (0) 2017.01.21
쿼트아이1) MySQL 익숙해지기.  (0) 2017.01.21

+ Recent posts