import java.io.*;
import java.net.*;
import javax.net.ssl.*;
public class testClass {
public static void main(String[] args) {
// TODO Auto-generated method stub
String urlStr = "https://car.jp.msn.com/rss/business.aspx";
try{
URL url = new URL(urlStr);
HttpURLConnection http = null;
if (url.getProtocol().toLowerCase().equals("https")) {
trustAllHosts();
HttpsURLConnection https = (HttpsURLConnection) url.openConnection();
https.setHostnameVerifier(DO_NOT_VERIFY);
http = https;
} else {
http = (HttpURLConnection) url.openConnection();
}
BufferedInputStream bis = new BufferedInputStream(http.getInputStream());
byte[] buffer = new byte[2048];
int length = 0;
byte[] contentBytes = null;
ByteArrayOutputStream baos = new java.io.ByteArrayOutputStream();
while ((length = bis.read(buffer)) >= 0) {
baos.write(buffer, 0, length);
}
contentBytes = baos.toByteArray();
String result = new String(contentBytes, "utf-8");
System.out.println(result);
bis.close();
baos.close();
}catch(Exception e) {
e.printStackTrace();
}
}
private static void trustAllHosts() {
// Create a trust manager that does not validate certificate chains
TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return new java.security.cert.X509Certificate[] {};
}
@Override
public void checkClientTrusted(
java.security.cert.X509Certificate[] chain,
String authType)
throws java.security.cert.CertificateException {
// TODO Auto-generated method stub
}
@Override
public void checkServerTrusted(
java.security.cert.X509Certificate[] chain,
String authType)
throws java.security.cert.CertificateException {
// TODO Auto-generated method stub
}
} };
// Install the all-trusting trust manager
try {
SSLContext sc = SSLContext.getInstance("TLS");
sc.init(null, trustAllCerts, new java.security.SecureRandom());
HttpsURLConnection
.setDefaultSSLSocketFactory(sc.getSocketFactory());
} catch (Exception e) {
e.printStackTrace();
}
}
final static HostnameVerifier DO_NOT_VERIFY = new HostnameVerifier() {
@Override
public boolean verify(String hostname, SSLSession session) {
return true;
}
};
}
2011년 9월 1일 목요일
jsp 소스 ssl증명서 없는 rss 가지고오기
<%@ page contentType = "text/html; charset=utf-8"%>
<%@ page import="java.io.*" %>
<%@ page import="java.net.*" %>
<%@ page import="javax.net.ssl.*" %>
<%
// TODO Auto-generated method stub
String urlStr = "https://car.jp.msn.com/rss/business.aspx";
try{
URL url = new URL(urlStr);
HttpURLConnection http = null;
if (url.getProtocol().toLowerCase().equals("https")) {
trustAllHosts();
HttpsURLConnection https = (HttpsURLConnection) url.openConnection();
https.setHostnameVerifier(DO_NOT_VERIFY);
http = https;
} else {
http = (HttpURLConnection) url.openConnection();
}
BufferedInputStream bis = new BufferedInputStream(http.getInputStream());
byte[] buffer = new byte[2048];
int length = 0;
byte[] contentBytes = null;
ByteArrayOutputStream baos = new java.io.ByteArrayOutputStream();
while ((length = bis.read(buffer)) >= 0) {
baos.write(buffer, 0, length);
}
contentBytes = baos.toByteArray();
String result = new String(contentBytes, "utf-8");
System.out.println(result);
request.setAttribute("msg", result);
bis.close();
baos.close();
}catch(Exception e) {
e.printStackTrace();
}
%>
<%!
private static void trustAllHosts() {
// Create a trust manager that does not validate certificate chains
TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return new java.security.cert.X509Certificate[] {};
}
public void checkClientTrusted(
java.security.cert.X509Certificate[] chain,
String authType)
throws java.security.cert.CertificateException {
// TODO Auto-generated method stub
}
public void checkServerTrusted(
java.security.cert.X509Certificate[] chain,
String authType)
throws java.security.cert.CertificateException {
// TODO Auto-generated method stub
}
} };
// Install the all-trusting trust manager
try {
SSLContext sc = SSLContext.getInstance("TLS");
sc.init(null, trustAllCerts, new java.security.SecureRandom());
HttpsURLConnection
.setDefaultSSLSocketFactory(sc.getSocketFactory());
} catch (Exception e) {
e.printStackTrace();
}
}
final static HostnameVerifier DO_NOT_VERIFY = new HostnameVerifier() {
public boolean verify(String hostname, SSLSession session) {
return true;
}
};
%>
${msg}
<%@ page import="java.io.*" %>
<%@ page import="java.net.*" %>
<%@ page import="javax.net.ssl.*" %>
<%
// TODO Auto-generated method stub
String urlStr = "https://car.jp.msn.com/rss/business.aspx";
try{
URL url = new URL(urlStr);
HttpURLConnection http = null;
if (url.getProtocol().toLowerCase().equals("https")) {
trustAllHosts();
HttpsURLConnection https = (HttpsURLConnection) url.openConnection();
https.setHostnameVerifier(DO_NOT_VERIFY);
http = https;
} else {
http = (HttpURLConnection) url.openConnection();
}
BufferedInputStream bis = new BufferedInputStream(http.getInputStream());
byte[] buffer = new byte[2048];
int length = 0;
byte[] contentBytes = null;
ByteArrayOutputStream baos = new java.io.ByteArrayOutputStream();
while ((length = bis.read(buffer)) >= 0) {
baos.write(buffer, 0, length);
}
contentBytes = baos.toByteArray();
String result = new String(contentBytes, "utf-8");
System.out.println(result);
request.setAttribute("msg", result);
bis.close();
baos.close();
}catch(Exception e) {
e.printStackTrace();
}
%>
<%!
private static void trustAllHosts() {
// Create a trust manager that does not validate certificate chains
TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return new java.security.cert.X509Certificate[] {};
}
public void checkClientTrusted(
java.security.cert.X509Certificate[] chain,
String authType)
throws java.security.cert.CertificateException {
// TODO Auto-generated method stub
}
public void checkServerTrusted(
java.security.cert.X509Certificate[] chain,
String authType)
throws java.security.cert.CertificateException {
// TODO Auto-generated method stub
}
} };
// Install the all-trusting trust manager
try {
SSLContext sc = SSLContext.getInstance("TLS");
sc.init(null, trustAllCerts, new java.security.SecureRandom());
HttpsURLConnection
.setDefaultSSLSocketFactory(sc.getSocketFactory());
} catch (Exception e) {
e.printStackTrace();
}
}
final static HostnameVerifier DO_NOT_VERIFY = new HostnameVerifier() {
public boolean verify(String hostname, SSLSession session) {
return true;
}
};
%>
${msg}
2011년 8월 13일 토요일
MYSQL 정리 02- (update)
http://www.yukun.info/blog/2008/11/mysql-update-delete-record.html
前回はレコードの検索クエリの作成方法を扱いましたが、今回は既存のレコードのフィールド値を更新するUPDATE文と、レコードを削除するDELETE文の練習をしてみます。
まず、扱うテーブル内のレコードの一覧を下記に示します。これは前回と同じです。
次に、UPDATE文で上の本を100円値下げしましょう。
上手くいったようですね。UPDATE文の一般構文は以下のようになります。
確かに、100円値下げしてありますね。
確かに、book_Gが削除されていますね。
http://www.abe-tatsuya.com/web_prog/mysql/update_inner_join.php
MySQL の update 文の中で inner join するには、以下のようにします。
前回はレコードの検索クエリの作成方法を扱いましたが、今回は既存のレコードのフィールド値を更新するUPDATE文と、レコードを削除するDELETE文の練習をしてみます。
まず、扱うテーブル内のレコードの一覧を下記に示します。これは前回と同じです。
1 2 3 4 5 6 7 8 9 10 11 12 | mysql> SELECT * FROM book_list;+---------+--------+--------+-------+-----------------------+| book_id | title | author | price | comments |+---------+--------+--------+-------+-----------------------+| 1 | book_A | auth_A | 1500 | good, bad, excellence || 2 | book_B | auth_B | 2900 | not bad, good || 3 | book_C | auth_C | 1800 | interesting, amazing || 4 | book_D | auth_D | 700 | sad, depress || 5 | book_E | auth_E | 1200 | good, funny || 6 | book_F | auth_C | 3500 | bored, difficult || 7 | book_G | auth_A | 400 | very good!, excellent |+---------+--------+--------+-------+-----------------------+ |
UPDATE文でレコードの更新
それでは試しに、「値段が1000円を超え2000円未満の本を100円値下げする」SQL文を書いてみます。最初は念のため修正するレコードをSELECT文で出力してみます。1 2 3 4 5 6 7 8 9 10 | mysql> SELECT * FROM book_list -> WHERE price > 1000 -> AND price < 2000;+---------+--------+--------+-------+-----------------------+| book_id | title | author | price | comments |+---------+--------+--------+-------+-----------------------+| 1 | book_A | auth_A | 1500 | good, bad, excellence || 3 | book_C | auth_C | 1800 | interesting, amazing || 5 | book_E | auth_E | 1200 | good, funny |+---------+--------+--------+-------+-----------------------+ |
1 2 3 4 5 6 | mysql> UPDATE book_list -> SET price = price - 100 -> WHERE price > 1000 -> AND price < 2000;Query OK, 3 rows affected (0.00 sec)Rows matched: 3 Changed: 3 Warnings: 0 |
UPDATE <テーブル名>
SET <更新する列名1> = <代入する値1> [, <更新列名2> = <代入値2>, ...]
WHERE <条件式>;WHERE句は省略可能です。SET句内のイコール「=」は代入演算子です(WHERE句の「=」は等価演算子)。複数のフィールドを書き換える際はSET句内の個々の代入式をカンマ「,」で区切ります。UPDATE文は条件に合致する全てのレコードをSET句で書き換えます。実際に書き変わったか確認してみましょう。1 2 3 4 5 6 7 8 9 10 | mysql> SELECT title, price FROM book_list -> WHERE price + 100 > 1000 -> AND price + 100 < 2000;+--------+-------+| title | price |+--------+-------+| book_A | 1400 || book_C | 1700 || book_E | 1100 |+--------+-------+ |
DELETE文でレコードを削除
一般構文は、DELETE FROM <テーブル名>
WHERE <条件式>;です。条件に合致する全てのレコードを削除します。1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | mysql> DELETE FROM book_list -> WHERE title = 'book_G';Query OK, 1 row affected (0.00 sec)mysql> SELECT title FROM book_list;+--------+| title |+--------+| book_A || book_B || book_C || book_D || book_E || book_F |+--------+ |
リファレンス
- MySQL :: MySQL 5.1 Reference Manual :: 12.2.12 UPDATE Syntax
- MySQL :: MySQL 5.1 Reference Manual :: 12.2.2 DELETE Syntax
http://www.abe-tatsuya.com/web_prog/mysql/update_inner_join.php
MySQL の update 文で inner join する
基本的な SQL 文は MySQL だろうが PostgreSQL だろうが、MS Access だろうが何だろうが、変わりはないんですが、一応メモ。MySQL の update 文の中で inner join するには、以下のようにします。
update table1 inner join table2 on table1.id = table2.id set table1.cellname1 = hoge where table2.cellname2 = 'huga';
MYSQL 정리 01- (SELECT)
http://www.yukun.info/blog/2008/11/mysql-query-select-where-in-like-between.html
author列がauth_Aに合致するレコードを検索し、そのtitle、price列を表示しています。「=」は等価演算子です(代入演算子ではありません)。ちなみに非等価演算子は「<>」です。
アスタリスク「*」はワイルドカードで全ての列を返します。
WHERE句内の複数の条件を結合する際はAND、ORキーワードを用います。
「%」は任意の文字列にマッチします。対して「_」任意の1文字にマッチします。
これを書き直すと、
確かに実行結果は合致していますね。
だだし、INキーワードではINの直前に書いてもOKです。
- SELECT文の基本形 – WHERE句
- 比較文字列内にワイルドカードを指定 – LIKEキーワード、「%」、「_」記号
- 比較範囲の指定 – BETWEENキーワード
- 複数のOR結合をIN句でまとめる
- NOTキーワードで条件の反転
- NULLフィールドの検索 – IS NULL、IS NOT NULL
SELECT文の基本形 – WHERE句
SELECT文では指定したテーブル(FROM句)に対して、検索条件(WHERE句)にマッチするレコード(行)の指定フィールド(列)を表示します。SELECTに続くのは列名、と覚えましょう。以下、具体例。SELECT <列名1>[, <列名2>, ...] FROM <テーブル名>
WHERE
<検索条件>;WHERE句は省略可能。1 2 3 4 5 6 7 8 9 | mysql> SELECT title, price FROM book_list -> WHERE -> author = 'auth_A';+--------+-------+| title | price |+--------+-------+| book_A | 1500 || book_G | 400 |+--------+-------+ |
1 2 3 4 5 6 7 8 9 10 | mysql> SELECT * FROM book_list -> WHERE -> price < 1500;+---------+--------+--------+-------+-----------------------+| book_id | title | author | price | comments |+---------+--------+--------+-------+-----------------------+| 4 | book_D | auth_D | 700 | sad, depress || 5 | book_E | auth_E | 1200 | good, funny || 7 | book_G | auth_A | 400 | very good!, excellent |+---------+--------+--------+-------+-----------------------+ |
1 2 3 4 5 6 7 8 9 10 11 | mysql> SELECT title, price FROM book_list -> WHERE -> price >= 1800 -> AND -> author = 'auth_C';+--------+-------+| title | price |+--------+-------+| book_C | 1800 || book_F | 3500 |+--------+-------+ |
比較文字列内にワイルドカードを指定 - LIKEキーワード、「%」、「_」記号
WHERE句内の比較条件に用いる演算子の一種と捉えてもいいかもしれません。1 2 3 4 5 6 7 8 9 | mysql> SELECT title, author, comments FROM book_list -> WHERE -> comments LIKE '%excellen%';+--------+--------+-----------------------+| title | author | comments |+--------+--------+-----------------------+| book_A | auth_A | good, bad, excellence || book_G | auth_A | very good!, excellent |+--------+--------+-----------------------+ |
比較範囲の指定 - BETWEENキーワード
price >= 1000 AND price <= 2000の様な条件を簡潔に書くことが出来ます。1 2 3 4 5 6 7 8 9 10 | mysql> SELECT title, price FROM book_list -> WHERE -> price >= 1000 AND price <= 2000;+--------+-------+| title | price |+--------+-------+| book_A | 1500 || book_C | 1800 || book_E | 1200 |+--------+-------+ |
1 2 3 4 5 6 7 8 9 10 | mysql> SELECT title, price FROM book_list -> WHERE -> price BETWEEN 1000 AND 2000;+--------+-------+| title | price |+--------+-------+| book_A | 1500 || book_C | 1800 || book_E | 1200 |+--------+-------+ |
複数のOR結合をIN句でまとめる
1 2 3 4 5 6 7 8 9 10 11 | mysql> SELECT title, author, price FROM book_list -> WHERE -> author IN ('auth_A', 'auth_C');+--------+--------+-------+| title | author | price |+--------+--------+-------+| book_A | auth_A | 1500 || book_C | auth_C | 1800 || book_F | auth_C | 3500 || book_G | auth_A | 400 |+--------+--------+-------+ |
NOTキーワードで条件の反転
LIKE、BETWEEN、IN句と共にも使用することが出来ます。その場合は通常比較フィールドの直前に書きます。1 2 3 4 5 6 7 8 9 10 | mysql> SELECT title, author, price FROM book_list -> WHERE -> NOT author IN ('auth_A', 'auth_C');+--------+--------+-------+| title | author | price |+--------+--------+-------+| book_B | auth_B | 2900 || book_D | auth_D | 700 || book_E | auth_E | 1200 |+--------+--------+-------+ |
1 2 3 4 5 6 7 8 9 10 | mysql> SELECT title, author, price FROM book_list -> WHERE -> author NOT IN ('auth_A', 'auth_C');+--------+--------+-------+| title | author | price |+--------+--------+-------+| book_B | auth_B | 2900 || book_D | auth_D | 700 || book_E | auth_E | 1200 |+--------+--------+-------+ |
NULLフィールドの検索 – IS NULL、IS NOT NULL
1 2 3 | mysql> SELECT * FROM book_list -> WHERE title IS NULL;Empty set (0.00 sec) |
1 2 3 4 5 6 7 8 9 10 11 12 13 | mysql> SELECT * FROM book_list -> WHERE title IS NOT NULL;+---------+--------+--------+-------+-----------------------+| book_id | title | author | price | comments |+---------+--------+--------+-------+-----------------------+| 1 | book_A | auth_A | 1500 | good, bad, excellence || 2 | book_B | auth_B | 2900 | not bad, good || 3 | book_C | auth_C | 1800 | interesting, amazing || 4 | book_D | auth_D | 700 | sad, depress || 5 | book_E | auth_E | 1200 | good, funny || 6 | book_F | auth_C | 3500 | bored, difficult || 7 | book_G | auth_A | 400 | very good!, excellent |+---------+--------+--------+-------+-----------------------+ |
リファレンス
2010년 11월 29일 월요일
mysql
■ Mysql 데몬 start 하기
# /usr/local/mysql/bin/mysqld_safe &
또는 # /usr/local/mysql/share/mysql/mysql.server start
■ Mysql 데몬 stop 하기
# /usr/local/mysql/bin/mysqladmin -uroot shutdown
또는 # /usr/local/mysql/share/mysql/mysql.server stop
■ Mysql 접속 방법
형식 : mysql -u 사용자 -p 사용DB
예제) # /usr/local/mysql/bin/mysql -u root -p mysql
Enter password: -> 초기 세팅후 비밀번호가 지정되지 않은경우는 엔터
또는
# /usr/local/mysql/bin/mysql mysql -p
Enter password:
■ mysql의 root암호설정법
mysql> update user SET Password=password(\'비밀번호\') where user=\'root\';
■ 일반계정의 비밀번호 변경시
mysql> update user set password=password(\'새비밀번호\') where user=\'계정명\';
■ DB 생성명령
mysql> create database DB명
■ DB 사용자 계정 생성 방법(각 버전 별 필드 수를 확인 하시어 이용하시면 됩니다.)
◊ mysql 3.xx 에서 생성방법
mysql> insert into user values(\'localhost\',\'계정명\',password(\'비밀번 호\'),\'N\',
\'N\',\'N\',\'N\',\'N\',\'N\',\'N\',\'N\',\'N\',\'N\',\'N\',\'N\',\'N\',\'N\');
mysql> insert into db values(\'localhost\',\'DB명\',\'계정명\',\'Y\',\'Y\',\'Y\',\'Y\',\'Y\',\'Y\',\'Y\',\'Y\',\'Y\',\'Y\');
mysql> FLUSH PRIVILEGES; (새로 만든 디비를 MYSQL에 적용하기 위하여 reload함)
◊ mysql 4.0.xx 에서 생성방법
mysql> insert into db values (\'localhost\',\'DB명\',\'DB계정명\',\'Y\',\'Y\',\'Y\',\'Y\',\'Y\',\'Y\',\'N \',\'Y\',\'Y\',\'Y\',\'Y\',\'Y\');
mysql> insert into user (host, user, password) values (\'localhost\',\'DB계정명\',password(\'비밀번호\'));
또는 아래와 같이도 생성가능함
mysql> INSERT INTO user VALUES (\'localhost\',\'DB계정명\',password(\'비밀번호\'),
\'N\',\'N\',\'N\',\'N\',\'N\',\'N\',\'N\',\'N\',\'N\',\'N\',\'N\',\'N\',\'N\',\'N\',\'N\',\'N\',\'N\',\'N\',\'N\',\'N\',\'N\',\'\',\'\',\'\',\'\',0,0,0);
mysql> FLUSH PRIVILEGES;
◊ mysql 4.1.xx 에서 생성방법
mysql> insert into user (host, user, password) values (\'localhost\',\'DB계정명\',password(\'비밀번호\'));
mysql> INSERT INTO db(Host,Db,User,Select_priv,Insert_priv,Update_priv,Delete_priv,Create_priv,Drop_priv)
VALUES(\'localhost\',\'DB명\',\'DB계정명\',\'Y\',\'Y\',\'Y\',\'Y\',\'Y\',\'Y\');
mysql> FLUSH PRIVILEGES;
● GRANT 로 생성하는 방법
mysql> GRANT ALL PRIVILEGES ON DB명.* TO DB계정명@localhost IDENTIFIED BY \'비밀번호\' WITH GRANT OPTION;
=> localhost에서 \'DB계정명\' 이라는 사용자를 등록시
mysql> GRANT ALL PRIVILEGES ON DB명.* TO DB계정명@\'%\' IDENTIFIED BY \'비밀번호\' WITH GRANT OPTION;
=> localhost 아닌 원격에서 접속시 호스트 부분을 % 로 해준다.
■ 계정,DB 생성 확인
mysql> select * from user;
■ 기타 mysql에서 자주 사용되는 명령들
▷ DB삭제시
mysql> drop database DB명
▷ DB 계정 삭제시
mysql> delete from user where user=\'DBuser\'; => (DBuser 라는 user 레코드를 삭제시)
mysql> delete from db where user=\'DB\'; => (DB 라는 db 레코드를 삭제시)
mysql> FLUSH PRIVILEGES;
▷ DB선택시
mysql> use DB명;
▷ DB 및 테이블 list보기
mysql> show databases;
mysql> show tables;
▷ mysql상의 테이블 정보 보기
mysql> show tables from mysql;
▷ DB table의 칼럼정보 보기
mysql> show columns from db;
▷ 테이블구조
mysql> describe 테이블명;
▷ 인덱스 보기
mysql> show index from 테이블명;
▷ 버전체크
mysql> select version();
▷ MySQL의 상태 보기
mysql> show status;
▷ MySQL 환경변수보기
mysql> show variables;
◆ mysql 백업 하기
# /usr/local/mysql/bin/mysqldump {-h 호스트} -u 사용자 -p DB명 > 백업파일명.sql
◆ mysql 복구 하기
# /usr/local/mysql/bin/mysql {-h 호스트} -u 사용자 -p DB명 < 백업파일명.sql
=> {-h 호스트}는 원격접속시나 호스트명이 별도로 분류되어 있는경우에 사용
◆ Mysql root 비밀번호를 분실한 경우 조치방법
1. 실행중인 msyql 종료
# killall mysqld 또는 killall -9 mysqld
# ps -ef | grep mysqld (mysql 데몬 없음을 확인)
2. grant-table 미사용모드로 mysql시작
(mysql 3.x 사용시)
# /usr/local/mysql/bin/safe_mysqld --skip-grant-tables &
(mysql 4.x 에서 사용시)
# /usr/local/mysql/bin/mysqld_safe --skip-grant-tables &
# /usr/local/mysql/bin/mysql -u root -p mysql
3. update문으로 root사용자 패스워드 설정
mysql> update user set password=password(\'newpasswd\') where user = \'root\';
mysql> flush privileges;
4. 실행중인 mysql 다시 종료
# killall mysqld 또는 killall -9 mysqld
# ps -ef | grep mysqld (mysql 데몬 없음을 확인)
5. Mysql 데몬 다시 시작
# /usr/local/mysql/bin/safe_mysqld &
# ps -ef | grep mysql
피드 구독하기:
글 (Atom)