public class DBConnection {
static PreparedStatement ps=null;
public static Connection getConnection() {
Connection con=null;
try {
//导入derbyclient.jar
Class.forName("org.apache.derby.jdbc.ClientDriver");
con=DriverManager.getConnection("jdbc:derby://127.0.0.1:1527/ys2;create=true","root", "1234");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return con;
}
}
/**内嵌模式*/
public class DBConnection2 {
static int i=1;
static Statement statement=null;
static ResultSet rs=null;
static PreparedStatement ps;
static String sql="create table ys(id int not null generated always as identity constraint pk primary key, name varchar(50), salary double default null )";
static String insert_sql="insert into ys(name,salary) values('ys',2000)";
public static Connection getConnection2() {
Connection con=null;
try {
//导入derby.jar
Class.forName("org.apache.derby.jdbc.EmbeddedDriver").newInstance();
// con=DriverManager.getConnection("jdbc:derby:内嵌数据库的位置;create=true(不存在就创建)","root", "1234");
con=DriverManager.getConnection("jdbc:derby:D:\\Workspaces02\\Myeclipse自带的Derby数据库\\ys","root", "1234");
//判断数据库表是否存在
DatabaseMetaData meta = con.getMetaData();
ResultSet rsTables = meta.getTables(null , null,"YS", null);
if(rsTables.next()){
System.out.println("表存在");
return con;
}else{
System.out.println("表不存在");
createTable(con);
return con;
}
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return con;
}