Created
March 30, 2011 10:10
-
-
Save seyan/894164 to your computer and use it in GitHub Desktop.
PreparedStatementサンプル(SQL Server)。複数パラメータを用いた検索を考慮。(検索条件項目が複数存在していて,いずれの項目も必須で無い場合)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* RDBMS 接続情報を集めたクラス | |
* | |
*/ | |
public class AccessData { | |
public static final String driverName = "com.microsoft.sqlserver.jdbc.SQLServerDriver"; | |
public static final String jdbcUrl = "jdbc:sqlserver://localhost:1433;DatabaseName=wasbookDB"; | |
public static final String userId = "dbusers"; | |
public static final String password = "dbusers"; | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 本一冊を表すクラス | |
* | |
*/ | |
public class Book { | |
private int id; | |
private String title; | |
private String author; | |
private String publisher; | |
private Date date; | |
private int price; | |
public Book(){ | |
} | |
public Book(int id, String title, String author, String publisher, Date date, int price){ | |
this.id = id; | |
this.title = title; | |
this.author = author; | |
this.publisher = publisher; | |
this.date = date; | |
this.price = price; | |
} | |
/** | |
* アクセス用メソッド | |
* | |
*/ | |
public void setId(int id) { | |
this.id = id; | |
} | |
public String getTitle() { | |
return title; | |
} | |
public void setTitle(String title) { | |
this.title = title; | |
} | |
public String getAuthor() { | |
return author; | |
} | |
public void setAuthor(String author) { | |
this.author = author; | |
} | |
public String getPublisher() { | |
return publisher; | |
} | |
public void setPublisher(String publisher) { | |
this.publisher = publisher; | |
} | |
public int getPrice() { | |
return price; | |
} | |
public void setPrice(int price) { | |
this.price = price; | |
} | |
public int getId() { | |
return id; | |
} | |
public void setDate(Date date){ | |
this.date = date; | |
} | |
public Date getDate() { | |
return date; | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.sql.Connection; | |
import java.sql.PreparedStatement; | |
import java.sql.ResultSet; | |
import java.sql.SQLException; | |
import java.util.ArrayList; | |
import java.util.List; | |
public class BookDAO { | |
private Connection con; | |
public BookDAO(Connection con){ | |
this.con = con; | |
} | |
public List<Book> searchBook(Book book){ | |
if(book == null){ | |
throw new IllegalArgumentException("引数bookがnullです。"); | |
} | |
List<Book> books = new ArrayList<Book>(); | |
ResultSet rset = null; | |
PreparedStatement pStmt = null; | |
String sql = "SELECT id, title, author, publisher, date, price FROM books" | |
+ " WHERE NULLIF(title, '') = COALESCE( ?, NULLIF(title, '')) " | |
+ " AND NULLIF(price, 0) <= COALESCE( ?, NULLIF(price, 0))"; | |
try{ | |
pStmt = con.prepareStatement(sql); | |
// SQL Serverはnullと空文字を区別するので同等に扱うために空文字をnullに変換する | |
if(book != null && "".equals( book.getTitle() ) ){ | |
book.setTitle(null); | |
} | |
pStmt.setString(1, book.getTitle()); | |
pStmt.setInt(2, book.getPrice()); | |
// クエリーを実行して結果セットを取得 | |
rset = pStmt.executeQuery(); | |
books = map(rset); | |
}catch(SQLException e){ | |
e.printStackTrace(); | |
}finally { | |
// DB接続オブジェクトをクローズ | |
if (rset != null) { | |
try{ | |
rset.close(); | |
}catch(SQLException e){ | |
e.printStackTrace(); | |
} | |
} | |
if(pStmt != null){ | |
try{ | |
pStmt.close(); | |
}catch(SQLException e){ | |
e.printStackTrace(); | |
} | |
} | |
if(con != null){ | |
try{ | |
con.close(); | |
}catch(SQLException e){ | |
e.printStackTrace(); | |
} | |
} | |
} | |
return books; | |
} | |
/** | |
* 引数で与えられたResultSetをList化したものを返す | |
* @param rset | |
*/ | |
private List<Book> map(ResultSet rset){ | |
if(rset == null){ | |
throw new IllegalArgumentException("引数rsetがnullです。"); | |
} | |
ArrayList<Book> list = new ArrayList<Book>(); | |
try { | |
while (rset.next()) { | |
list.add(new Book(rset.getInt("id"), rset.getString("title"), rset.getString("author"), rset.getString("publisher"), rset.getDate("date"), rset.getInt("price"))); | |
} | |
} catch (SQLException e) { | |
e.printStackTrace(); | |
} | |
return list; | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.sql.Connection; | |
import java.sql.DriverManager; | |
import java.sql.SQLException; | |
import java.util.ArrayList; | |
public class Page131 { | |
public static void main(String[] args) { | |
Book book = new Book(); | |
book.setTitle(""); | |
book.setPrice(1300); | |
Connection con = null; | |
try{ | |
Class.forName(AccessData.driverName); | |
con = DriverManager.getConnection(AccessData.jdbcUrl, AccessData.userId, AccessData.password); | |
con.setAutoCommit(false); | |
BookDAO dao = new BookDAO(con); | |
ArrayList<Book> list = (ArrayList<Book>) dao.searchBook(book); | |
printList(list); | |
}catch(ClassNotFoundException e){ | |
e.printStackTrace(); | |
}catch(SQLException e){ | |
try{ | |
con.rollback(); | |
}catch(SQLException ex){ | |
ex.printStackTrace(); | |
} | |
}finally{ | |
try{ | |
if(con != null){ | |
con.close(); | |
} | |
}catch(SQLException e){ | |
e.printStackTrace(); | |
} | |
} | |
} | |
private static void printList(ArrayList<Book> books){ | |
for(Book b : books){ | |
System.out.println(b.getId()); | |
System.out.println(b.getTitle()); | |
System.out.println(b.getAuthor()); | |
System.out.println((b.getPublisher())); | |
System.out.println(b.getPrice()); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
【レビュー後に変更した点】
propertiesファイルを使用するようにした。
loggingツールを使用するようにした。
Connetionオブジェクトのクローズ位置を変更した。(開いたクラスが閉じるべきであるため。)
java.sql.dateは問題児(javaのDateとSQLのDateでは、細かい部分が異なっており問題の原因となることがあるため)なので安易に使わない。SQLserverから文字列で日付を取得後、Javaでutil.Dateに変換して用いることとした。
BookSearchCondition(検索条件を保持するクラス)を削除し、検索条件はBookに保持させることにした。
下位クラスへのキャスト(ListをArrayListにキャストしたり)は行ってはいけないので、修正。
【メモ】
SQL Serverは列別名が使えない…。