Hsqldb 简明教程
HSQLDB - Connect
在安装章节中,我们讨论了如何手动连接数据库。在此章节中,我们将讨论如何以编程方式连接数据库(使用 Java 编程)。
In the installation chapter, we discussed how to connect the database manually. In this chapter, we will discuss how to connect the database programmatically (using Java programming).
看看以下程序,它将启动服务器并在 Java 应用程序和数据库之间建立连接。
Take a look at the following program, which will start the server and create a connection between the Java application and the database.
Example
import java.sql.Connection;
import java.sql.DriverManager;
public class ConnectDatabase {
public static void main(String[] args) {
Connection con = null;
try {
//Registering the HSQLDB JDBC driver
Class.forName("org.hsqldb.jdbc.JDBCDriver");
//Creating the connection with HSQLDB
con = DriverManager.getConnection("jdbc:hsqldb:hsql://localhost/testdb", "SA", "");
if (con!= null){
System.out.println("Connection created successfully");
}else{
System.out.println("Problem with creating connection");
}
} catch (Exception e) {
e.printStackTrace(System.out);
}
}
}
将此代码保存到 ConnectDatabase.java 文件中。您需要使用以下命令启动数据库。
Save this code into ConnectDatabase.java file. You will have to start the database using the following command.
\>cd C:\hsqldb-2.3.4\hsqldb
hsqldb>java -classpath lib/hsqldb.jar org.hsqldb.server.Server --database.0
file:hsqldb/demodb --dbname.0 testdb
您可以使用以下命令编译并执行代码。
You can use the following command to compile and execute the code.
\>javac ConnectDatabase.java
\>java ConnectDatabase
在执行上述命令之后,您将收到以下输出−
After execution of the above command, you will receive the following output −
Connection created successfully