First crate a Database in Derby
Derby
Apache Derby, an is an open source relational database implemented entirely in Java.
Refer http://db.apache.org/derby/
Refer http://db.apache.org/derby/
(I used windows as operating system and created database in my "E" drive)
Open Command Prompt(Run => cmd)
Open Command Prompt(Run => cmd)
- Run Derby ij Toll
E:\>java -jar "C:\Program Files\Java\jdk1.7.0_21\db\lib\derbyrun.jar" ij
- Create a Data Base (I named it as 'mydb')
ij> CONNECT 'jdbc:derby:mydb;create=true';
ij> create table mytable ( > ID int, > NAME varchar(15)); 0 rows inserted/updated/deleted
ij>INSERT INTO MYTABLE VALUES (001 , 'JAVA'), (002, 'Derby'), (003, 'Database'); 3 rows inserted/updated/deleted
import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.Statement; public class DerbyTest { private Connection connect = null; private Statement statement = null; private ResultSet resultSet = null; public DerbyTest() throws Exception { try { Class.forName("org.apache.derby.jdbc.EmbeddedDriver").newInstance(); connect = DriverManager .getConnection("jdbc:derby:e:/mydb"); PreparedStatement statement = connect .prepareStatement("SELECT * FROM MYTABLE"); resultSet = statement.executeQuery(); while (resultSet.next()) { String id = resultSet.getString("ID"); String name = resultSet.getString("NAME"); System.out.println("ID: " + id); System.out.println("NAME: " + name); } } catch (Exception e) { throw e; } finally { close(); } } private void close() { try { if (resultSet != null) { resultSet.close(); } if (statement != null) { statement.close(); } if (connect != null) { connect.close(); } } catch (Exception e) { } } public static void main(String[] args) throws Exception { DerbyTest dao = new DerbyTest(); } }
E:/>javac DerbyTest.java
E:/>java DerbyTest
ID: 1 NAME: JAVA ID: 2 NAME: Derby ID: 3 NAME: Database
No comments:
Post a Comment