我是Big Java 4th的一些练习代码,用于将我的程序连接到derby数据库。不过,我每次都会收到以下内容。
Usage: java -classpath driver_class_path;. TestDB database.properties
作为输出,我不明白为什么它不会连接。
这是我的测试数据库:
public class TestDB
{
public static void main(String[] args) throws Exception
{
if (args.length == 0)
{
System.out.println(
"Usage: java -classpath driver_class_path"
+ File.pathSeparator
+ ". TestDB database.properties");
return;
}
else
SimpleDataSource.init(args[0]); `
Connection conn = SimpleDataSource.getConnection();
try
{
Statement stat = conn.createStatement();
stat.execute("CREATE TABLE Test (Name CHAR(20))");
stat.execute("INSERT INTO Test VALUES ('Romeo')");
ResultSet result = stat.executeQuery("SELECT * FROM Test");
result.next();
System.out.println(result.getString("Name"));
stat.execute("DROP TABLE Test");
}
finally
{
conn.close();
}
}
}
这是提供的连接程序:
public class SimpleDataSource
{
private static String url;
private static String username;
private static String password;
/**
Initializes the data source.
@param fileName the name of the property file that
contains the database driver, URL, username, and password
*/
public static void init(String fileName)
throws IOException, ClassNotFoundException
{
Properties props = new Properties();
FileInputStream in = new FileInputStream(fileName);
props.load(in);
String driver = props.getProperty("jdbc.driver");
url = props.getProperty("jdbc:url");
username = props.getProperty("jdbc.username");
if (username == null) username = "";
password = props.getProperty("jdbc.password");
if (password == null) password = "";
if (driver != null)
Class.forName(driver);
}
/**
Gets a connection to the database.
@return the database connection
*/
public static Connection getConnection() throws SQLException
{
return DriverManager.getConnection(url, username, password);
}
}
usage
方法告诉您如何正确运行程序。让我把它翻译成英语,以防出于某种原因,你得到这个代码的地方无法解释它。
用法:
在这里,我们将展示如何在命令提示符下使用该程序。如果从IDE运行程序,它将是类似的,但您将省略"java",类路径和程序名称将分别配置。
java
运行Java程序的命令
-类路径driver_class_path;。
将类路径指定为Derby驱动程序的位置,然后指定当前目录(程序所在的目录)
TestDB
你的程序的名称-它是TestDB,所以不要更改这个
database.properties
要使用的属性文件的文件名。属性文件包含数据库连接参数。这是软件开发的良好实践!数据库密码(如果有)必须与您设置的密码匹配。