Mag*_*lex 15
在Java中,您使用JDBC驱动程序与数据库进行标准化通信.您选择使用SQLLite可能没问题(听起来您正在尝试学习基础RESTful Web服务).对于"真正的"应用程序,您可能会选择其他一些数据库,如PostgreSQL或MySQL.
Xerials sqlite-jdbc似乎是SQLite的JDBC驱动程序的流行实现.
使用Maven,您需要做的就是为pom.xml添加依赖项.然后,Maven将下载jar和任何必要的依赖项,并允许您在应用程序中使用它:
<dependencies>
<dependency>
<groupId>org.xerial</groupId>
<artifactId>sqlite-jdbc</artifactId>
<version>3.7.2</version>
</dependency>
</dependencies>
Run Code Online (Sandbox Code Playgroud)
有关如何设置连接并对数据库运行查询的示例,Xerial sqlite-jdbc主页上的示例示例似乎是最好的起点:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class Sample
{
public static void main(String[] args) throws ClassNotFoundException
{
// load the sqlite-JDBC driver using the current class loader
Class.forName("org.sqlite.JDBC");
Connection connection = null;
try
{
// create a database connection
connection = DriverManager.getConnection("jdbc:sqlite:sample.db");
Statement statement = connection.createStatement();
statement.setQueryTimeout(30); // set timeout to 30 sec.
statement.executeUpdate("drop table if exists person");
statement.executeUpdate("create table person (id integer, name string)");
statement.executeUpdate("insert into person values(1, 'leo')");
statement.executeUpdate("insert into person values(2, 'yui')");
ResultSet rs = statement.executeQuery("select * from person");
while(rs.next())
{
// read the result set
System.out.println("name = " + rs.getString("name"));
System.out.println("id = " + rs.getInt("id"));
}
}
catch(SQLException e)
{
// if the error message is "out of memory",
// it probably means no database file is found
System.err.println(e.getMessage());
}
finally
{
try
{
if(connection != null)
connection.close();
}
catch(SQLException e)
{
// connection close failed.
System.err.println(e);
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
11775 次 |
| 最近记录: |