日期:2014-05-16 浏览次数:20488 次
关于javaDB的介绍就不说了,直接上例子。
首先将derby.jar添加到classpath下面(IDE的话直接引入)
?
import java.sql.*; import java.util.*; import java.io.*; public class Test { public static void main(String[] args) throws Exception{ DBHelper db = new DBHelper(); db.createUserTable(); db.insertUser(1,"zhangsan2","123"); db.insertUser(1,"zhangsan3","1233"); db.insertUser(1,"zhangsan4","1234"); db.insertUser(1,"zhangsan5","12345"); ResultSet rs = db.query(); while(rs.next()){ int id = rs.getInt("id"); String name = rs.getString("name"); String pwd = rs.getString("password"); System.out.println("id->" + id + "\tname->" + name + "\tpassword->" + pwd); } rs.close(); } } /** * 数据库工具类 */ class DBHelper { private Connection con = null ; //连接 public DBHelper(){ //loadDriver("org.apache.derby.jdbc.EmbeddedDriver"); //load driver jdk6可以省略加载驱动这一步 getConnection(); //init Connection } //load driver class private void loadDriver(String driveName){ try{ Class.forName(driveName); }catch(Exception e){ e.printStackTrace(); System.out.println("load driver failure"); } } //get Connection private void getConnection(){ try{ //con = DriverManager.getConnection("jdbc:derby:userDB;create=true;user=test;password=test"); //userDB创建在class运行目录 //con = DriverManager.getConnection("jdbc:derby:a/b/userDB;create=true;user=test;password=test"); //userDB创建在class下面的a/b文件夹下面, con = DriverManager.getConnection("jdbc:derby:d:/a/b/userDB;create=true;user=test;password=test"); //userDB创建在d盘下面的a/b文件夹下面, }catch(Exception e){ e.printStackTrace(); } } //create simple table for test public void createUserTable(){ try{ Statement stat = con.createStatement(); String sql_create = "create table tb_user(id int,name varchar(20),password varchar(20))"; stat.execute(sql_create); stat.close(); }catch(Exception e){ e.printStackTrace(); } } //insert user info public void insertUser(int id,String name,String pwd){ String sql_insert = "insert into tb_user values (?,?,?)"; try{ PreparedStatement pst = con.prepareStatement(sql_insert); pst.setInt(1,id); pst.setString(2,name); pst.setString(3,pwd); int i = pst.executeUpdate(); }catch(Exception e){ e.printStackTrace(); } } //query user info public ResultSet query(){ String sql_insert = "select * from tb_user"; try{ PreparedStatement pst = con.prepareStatement(sql_insert); return pst.executeQuery(); }catch(Exception e){ e.printStackTrace(); } return null; } }
?
?
?result:
---------- 直接运行 ----------
id->1?name->zhangsan2?password->123
id->1?name->zhangsan3?password->1233
id->1?name->zhangsan4?password->1234
id->1?name->zhangsan5?password->12345
Output completed (7 sec consumed) - Normal Termination
?
?