步骤
1. 打开命令shell,并转到将来存有数据库文件的目录
2. 定位derbyrun.jar。一般在jdk/db/lib目录中,我们使用derby来表示包含了lib/derbyrun.jar的目录
3. 运行命令:java -jar derby/lib/derbyrun.jar server start
4. 检查数据库是否工作了,然后创建一个名为 ij.properties 并包含下面各行的文件:
ij.driver=org.apache.derby.jdbc.ClientDriver
ij.protocol=jdbc:derby://localhost:1527/
#当COREJAVA数据库不存在,创建一个
ij.database=COREJAVA;create=true
在另一个命令shell中,通过执行下面的命令来运行Derby 的交互式脚本执行工具(称为ij): java -jar derby/lib/derbyrun.jar ij -p ij.properties
注:应该在ij.properties文件目录下打开命令shell
现在可以使用SQL 命令了,每条命令都应以分号结尾,要退出编辑器,可以键入“EXIT;”
最后在使用完数据库时,可以用该命令关闭服务器: java -jar derby/lib/derbyrun.jar server shutdown
注:路径在windows下应该是”\”
Java 连接Derby数据库实例
//database.properties文件
#jdbc.drivers=org.apache.derby.jdbc.ClientDriver 因为derby驱动程序将自动注册驱动类
jdbc.url=jdbc:derby://localhost:1527/COREJAVA
#jdbc.username=dbuser4 可以不使用用户名和密码,默认是APP用户,因为如果使用了如此的设置在第二次创建时(第一次中途失败)会出现 #org.apache.derby.client.am.SqlException: Schema“DBUSER4”中已经存在Table/View“GREETINGS”的异常,便于方便,所以在此注释掉了。
#jdbc.password=secret4
//需要注意的是在通过Derby交互式脚本执行工具删除表时,在不同的用户创建了相同的表时(当你如上设置了用户和密码,derby将自动为你创建用户),应按 DROP TABLE 用户名.表名 执行删除表操作
//java文件
import java.nio.file.*;
import java.sql.*;
import java.io.*;
import java.util.*;
/*
*This program tests that the database and the JDBC driver are correctly configured.
*/
public class TestDB{
public static void main(String[] args) throws IOException{
try{
runTest();
}catch(SQLException ex){
for(Throwable t:ex)
t.printStackTrace();
}
}
/**
*Runs a test by creating a table,adding a value,showing the table contents,and removing the table.
*/
public static void runTest() throws SQLException,IOException{
try(Connection conn = getConnection())
{
Statement stat = conn.createStatement();
stat.executeUpdate("CREATE TABLE Greetings (Message CHAR(40))");
// Using ' not "
stat.executeUpdate("INSERT INTO Greetings VALUES('hello')");
stat.executeUpdate("INSERT INTO Greetings VALUES('你好,世界')");
try(ResultSet result = stat.executeQuery("SELECT * FROM Greetings")){
//将光标移动到下一行,初始在第一行之前
while(result.next())
System.out.println(result.getString("Message"));
}
stat.executeUpdate("DROP TABLE Greetings");
}
}
/**
*Gets a connection from the properties specified in the file database.properties.
*@return the database connection
*/
public static Connection getConnection() throws SQLException,IOException{
Properties props = new Properties();
try(InputStream in = Files.newInputStream(Paths.get("database.properties"))){
props.load(in);
}
String drivers = props.getProperty("jdbc.drivers");
//为了适应那些不能自动注册的数据库驱动程序
if(drivers != null)
//这种方式可以提供多个驱动器,使用冒号分割
System.setProperty("jdbc.drivers",drivers);
String url = props.getProperty("jdbc.url");
String username = props.getProperty("jdbc.username");
String password = props.getProperty("jdbc.password");
return DriverManager.getConnection(url,username,password);
}
}
以上内容和代码来源于Java 核心技术卷Ⅱ (原书第九版)
--------------------
作者:吾在八月生
来源:优快云
原文:https://blog.youkuaiyun.com/ai_xao/article/details/78475833?utm_source=copy
版权声明:本文为博主原创文章,转载请附上博文链接!