我直接在 C:\ 中下载了 derby 并设置了 DERBY_INSTALL 和 CLASSPATH 变量:
C:\>set DERBY_INSTALL=C:\Apache\db-derby-10.9.1.0-bin
C:\>set CLASSPATH=%DERBY_INSTALL%\lib\derby.jar;%DERBY_INSTALL%\lib\derbytools.jar;.
C:\> cd %DERBY_INSTALL%\bin
C:\db-derby-10.9.1.0-bin\bin>java org.apache.derby.tools.ij
ij version 10.9
ij>
所以它显示了 ij>,我可以使用命令行 SQL 语句创建一个数据库。但我必须使用 Java 代码创建数据库及其表。所以我下面的源代码,但我不知道在哪里粘贴它以及如何运行它。当我将它粘贴到 db-derby-10.9.1.0-bin>bin 文件夹中并尝试使用“java MainClass komaldb C:\”在该文件夹中运行它时,它显示无法找到或加载主类 MainClass。我不确定我必须从哪里运行 java 程序。
Java 源代码:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
public class MainDB {
static Connection conn;
public static void main(String[] args) throws Exception {
if (args.length != 2) {
System.out.println("Usage: java JavaDBDemo <Name> <Address>");
System.exit(1);
}
String driver = "org.apache.derby.jdbc.EmbeddedDriver";
String dbName = "AddressBookDB";
String connectionURL = "jdbc:derby:" + dbName + ";create=true";
String createString = "CREATE TABLE ADDRESSBOOKTbl (NAME VARCHAR 32) NOT NULL,
ADDRESS VARCHAR(50) NOT NULL)";
Class.forName(driver);
conn = DriverManager.getConnection(connectionURL);
Statement stmt = conn.createStatement();
stmt.executeUpdate(createString);
PreparedStatement psInsert = conn
.prepareStatement("insert into ADDRESSBOOKTbl values (?,?)");
psInsert.setString(1, args[0]);
psInsert.setString(2, args[1]);
psInsert.executeUpdate();
Statement stmt2 = conn.createStatement();
ResultSet rs = stmt2.executeQuery("select * from ADDRESSBOOKTbl");
System.out.println("Addressed present in your Address Book\n\n");
int num = 0;
while (rs.next()) {
System.out.println(++num + ": Name: " + rs.getString(1) + "\n Address"
+ rs.getString(2));
}
rs.close();
}
}