JavaでSELECT結果とRETURNコードを吐き出すストアドを叩いて見る

理解できること

  • JavaからSQLServerのストアドの叩き方
  • 日付パラメーターの扱い
  • SELECT結果とReturn値の両方を返すストアドからの値取得
  • 初歩的なJDBCプログラミングの作法

ストアド

NorthWindをSQLServer2014 Expressにインストール
各インストール方法は割愛します。
対象プロシージャーは下記のようにちょっとかえてSELECT結果とreturnを返すようにしている。

USE [Northwind]
GO
/****** Object:  StoredProcedure [dbo].[Employee Sales by Country]    Script Date: 2017/01/27 15:37:04 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

ALTER procedure [dbo].[Employee Sales by Country] 
@Beginning_Date DateTime, @Ending_Date DateTime AS
SELECT Employees.Country, Employees.LastName, Employees.FirstName, Orders.ShippedDate, Orders.OrderID, "Order Subtotals".Subtotal AS SaleAmount
FROM Employees INNER JOIN 
	(Orders INNER JOIN "Order Subtotals" ON Orders.OrderID = "Order Subtotals".OrderID) 
	ON Employees.EmployeeID = Orders.EmployeeID
WHERE Orders.ShippedDate Between @Beginning_Date And @Ending_Date
RETURN 10

Java

これをJavaから叩いてみる。
別途MSからJDBCのjarをダウンロードして突っ込んでビルドパス通しておく。
あとは一般的なJDBCプロミングと変わらないけれど、
ResultSetの取得後にReturn値の取得という順番でいかないとダメっぽい。

import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;


public class Main {

	private static final String JDBC_URL="jdbc:sqlserver://localhost:1433;databaseName=NorthWind";
	private static final String USER = "sa";
	private static final String PWD = "xxxxxx";
	
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		Connection con = null;
		CallableStatement cs = null;
		ResultSet rs = null;
		String sql = "{? = call dbo.[Employee Sales by Country](@Beginning_Date = ? ,@Ending_Date = N'1997/07/01' )}";
			
		try {
			Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
			con = DriverManager.getConnection(JDBC_URL,USER,PWD);
			cs = con.prepareCall(sql);
			cs.registerOutParameter(1, java.sql.Types.INTEGER);
			cs.setDate(2, java.sql.Date.valueOf("1997-01-01"));
			
			if(! cs.execute()){
				System.out.println("Execution failed");
			}
			
			rs = cs.getResultSet();
			
			while(rs != null && rs.next()){
				System.out.print(rs.getObject(1) + "\t");
				System.out.print(rs.getObject(2) + "\t");
				System.out.print(rs.getObject(3) + "\t");
				System.out.print(rs.getObject(4) + "\t");
				System.out.print(rs.getObject(5) + "\t");
				System.out.println("");
			}
			// 順番大事
			int retCode = cs.getInt(1);
			System.out.println(retCode);

		} catch (Exception e){
			e.printStackTrace();
		} finally {
			forceClose(rs);
			forceClose(cs);
			forceClose(con);
		}
	
	}

	private static void forceClose(AutoCloseable c) {
        if (c == null) {
            return;
        }
        try {
            c.close();
        }
        catch (Exception ignore) {
           ignore.printStackTrace();
        }
    }

}

出力結果

USA	Callahan	Laura	1997-01-16 00:00:00.0	10380	
USA	Fuller	Andrew	1997-01-01 00:00:00.0	10392	
USA	Davolio	Nancy	1997-01-03 00:00:00.0	10393	
USA	Davolio	Nancy	1997-01-03 00:00:00.0	10394	
UK	Suyama	Michael	1997-01-03 00:00:00.0	10395	
USA	Davolio	Nancy	1997-01-06 00:00:00.0	10396
 .....
10	


10年ぶりにSQLServer触ったけどなかなかよいね。Management Studioのできはやはり秀逸。

ゼロから始めるDeep Learning<2日目>

#! /usr/bin/env python3

import numpy as np

x = np.array([1.0,2.0,3.0])
print(x)
print(type(x))

y = np.array([2.0,4.0,6.0])

print(x + y)
print(x * y)
print(x / 2)

A = np.array([[1,2],[3,4]])
print(A)
A.shape
A.dtype

B = np.array([[3,0],[0,6]])
print(A + B)
print(A * B)

print(A * 10)

# ベクトルや行列を一般化したものをテンソルと呼びます。

for row in A:
    print(row)

for row in B:
    for i in row:
        print(i)
        
X = np.array([[51,55],[14,19],[0,4]])
XX = X.flatten()
print(XX)
print(XX[np.array([0,2,4])])

print(XX[XX>15])

import matplotlib.pyplot as plt
from matplotlib.image import imread
 
x = np.arange(0,6,0.1) # 0から6まで0.1刻みで生成
y = np.sin(x)
plt.plot(x,y)
# plt.show()

img = imread('1.5.jpg')
plt.imshow(img)
plt.show()

特にハマるところもなく。サクッと。今日まででPythonの文法終わり。明日からいよいよ。

機械学習かIoTか

どちらもこれから楽しんでいく分野だと思うんですよね。
でも宮川さんのRebuildでIoTはイテレーションが長くてたるいって言っていたのでとりま機械学習をする作戦に。
会社で読書会やりましょといってみたけれど。
忙しいと一蹴された。残念。

ゼロから作るDeep Learning開始

機械学習はウェーブの最終段階に来てると思うんですね。
ここで追いついておかないと致命的に時代遅れになると。

9/24にオライリーから出た書籍を使って勉強することにしました。
作者日本人でよく知らん人だけどあんたに賭けてみるよ。python界隈では有名人なのかもしれないが、界隈知らんので知らん人だ。

ゼロから作るDeep Learning ―Pythonで学ぶディープラーニングの理論と実装

ゼロから作るDeep Learning ―Pythonで学ぶディープラーニングの理論と実装

オライリーなのでひたすら分厚い本を覚悟してたけれどコンパクトで印象++
初めての本格的なPythonというのも楽しみ。

今日はPythonの基礎の基礎の文法のセクションでした。半分ぐらいしかやれてないけれど。

環境構築はhomebrewを使いました。
qiita.com
s/python/python3/でインストール。python3という名前でpython3がインストールされます。
pipもpip3としてインストールされるのでまぁ問題なし。ライブラリのインストールもさくっと。
pipの自己アップデートは失敗したけどまぁ、問題ないかな。。

今日のプログラム。
ifさえアレばなんとかなるってschemeで覚えたからもうコレで十分かといまは思っておく。
tupleとかあったなぁ。内包表記?だっけ。あったなぁ。忘れてる。
emacspython-modeが悪くない。ac-modeつけて、(の補完も設定すればわりかしストレスフリー

#! /usr/bin/env python3

a = [1,2,3,4,5]
print(len(a))
a[0]
a[4] = 99
print(a)
# print(a[5]) error

me = {'height' : 180}
me['height']
me['weight'] = 60
print(me)

# boolean
hungry = True
hoge = False

# if
if hungry:
    print("hungry")
else:
    print("not hungry")

for i in [1,2,3]:
    print(i)

def hello():
    print("Hello World")

hello()

class Man:
    def __init__(self,name):
        self.name = name
        print("constructor")

    def hello(self):
        print("Hello " + self.name + "!")

    def goodbye(self):
        print("Good Bye " + self.name + "!")

m = Man("David")
m.hello()
m.goodbye()

サーバーに侵入された

サーバーに侵入されましたよ。
原因はアップローダー。
phpスクリプトアップロードされて実行されてしまった。
getAdmin.phpとか名前がやべぇよ。

いやはや。迂闊でしたよ。index.php書き換えられてビビった。

というわけで対策。

Options +Indexes
RemoveType .php
RemoveHandler .php
<FilesMatch \.cgi$>
    SetHandler text/plain
</FilesMatch>
<FilesMatch \.php$>
    SetHandler text/plain
</FilesMatch>
<FilesMatch \.pl$>
    SetHandler text/plain
</FilesMatch>
<FilesMatch \.rb$>
    SetHandler text/plain
</FilesMatch>
<FilesMatch \.py$>
    SetHandler text/plain
</FilesMatch>

まぁ、そこそこ。ホントはすべてtext/plainにしたいのですけれども。

また侵入された

今度は

Options +Indexes -ExecCGI
php_flag engine off
AddType text/plain php

としました。

Apache->glassfish->jenkins/gitbucketのapacheの設定

warで落としてきたjenkinsとかをapache経由でglassfishで動かす。

a2enmod proxy
a2enmod proxy_http
a2enmod headers

して

ProxyPreserveHost On
ProxyPass         /jenkins  http://localhost:8080/jenkins nocanon
ProxyPassReverse  /jenkins  http://localhost:8080/jenkins
ProxyRequests     Off
AllowEncodedSlashes NoDecode
<Proxy http://localhost:8080/jenkins*>
  Order deny,allow
  Allow from all
</Proxy>
ProxyPass /gitbucket http://localhost:8080/gitbucket
ProxyPassReverse /gitbucket https://localhost:8080/gitbucket

ProxyPreserveHost On
ないとloalhost:8080/jenkinsとかにリダイレクトされる。

glassfishJavaEEの参照実装なのでこれから使う機会も増えると思う。こういうノウハウは蓄積していきたい。

管理コンソールとかも充実しまくりなのでglassfishは使っていきたい。

h2o->apache->glassfish->jenkinsとかになって良い感じ