/* * Copyright 2013 Websquared, Inc. * * Licensed 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. */ package org.fastcatsearch.ir.db; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import junit.framework.TestCase; public class DBTest extends TestCase{ public void testCreate() throws SQLException{ String DB_NAME = "TESTDB"; Connection conn = null; Statement st = null; ResultSet rs = null; try { Class.forName("org.apache.derby.jdbc.EmbeddedDriver").newInstance(); } catch (Exception e) { e.printStackTrace(); } try { conn = DriverManager.getConnection("jdbc:derby:"+DB_NAME); } catch (SQLException e) { //if DB is not created. conn = createDB(DB_NAME); System.out.println("conn = "+conn); if(conn == null){ throw new SQLException(e.toString()); }else{ initDB(conn); } } //use sql try { st = conn.createStatement(); st.executeUpdate("insert into DIC(dickey,count,value) values ('홍삼',3,'정관장,한삼인,홍삼아')"); rs = st.executeQuery("select * from DIC"); while(rs.next()){ System.out.println(rs.getString(1)+"/"+rs.getString(2)+"/"+rs.getString(3)+"/"+rs.getString(4)); } } catch (Exception e) { e.printStackTrace(); } finally{ try { rs.close(); st.close(); conn.close(); } catch (SQLException e) { e.printStackTrace(); } } } private void initDB(Connection conn) { Statement st = null; try { st = conn.createStatement(); // st.execute("drop table DIC"); st.execute("create table DIC (id int generated by default as identity primary key,dickey varchar(10) not null,count int not null,value varchar(255))");// 建表 } catch (SQLException e) { e.printStackTrace(); } finally{ try { st.close(); } catch (SQLException e) { e.printStackTrace(); } } } private Connection createDB(String dbName) { try { System.out.println("Create DB = "+dbName); return DriverManager.getConnection("jdbc:derby:"+dbName+";create=true"); } catch (SQLException e) { } return null; } }