请提供如何在Tomcat 6中使用SQLite的步骤,我正在使用Xerial SQLite JDBC驱动程序。在我的应用程序中,我有多个SQLite数据库(.db文件),根据用户登录情况需要连接到不同的SQLite数据库。我应该把所有的.db文件放在哪里?是放在webapp根目录下还是系统的任何位置或WEB-INF目录中?谢谢!
现在设置您的应用程序。如果您没有META-INF/context.xml文件,则创建一个。这是一个最小的文件:
<?xml version="1.0" encoding="UTF-8"?>
<Context>
<Resource name="jdbc/yourdb"
auth="Container"
type="javax.sql.DataSource"
driverClassName="org.sqlite.JDBC"
url="jdbc:sqlite:/${catalina.home}/dbs/yourDB.db"
factory="org.apache.tomcat.dbcp.dbcp.BasicDataSourceFactory">
</Resource>
</Context>
然后将以下内容添加到WEB-INF / web.xml中:
<resource-ref>
<description>Reviews Database</description>
<res-ref-name>jdbc/yourdb</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
现在,您应该可以开始了。这是一些访问数据库的示例代码(我有一个名为“admin”的表格,其中包含一个名为“username”的列):
public String getName() {
LOG.info("getting name : " + this.name);
try {
Context ctx = new InitialContext();
DataSource ds = (DataSource)ctx.lookup("java:comp/env/jdbc/yourdb");
Connection conn = ds.getConnection();
Statement stat = conn.createStatement();
ResultSet rs = stat.executeQuery("select username from admin");
this.name = rs.getString(1);
} catch (SQLException se) {
LOG.info(se.toString());
} catch (NamingException ne) {
LOG.info(ne.toString());
}
return this.name;
}
/**
*
* @param driverClassName
* @param url
* @param user
* @param password
* @throws SQLException
* @throws Exception
*/
public DefaultJdbcTransaction(String driverClassName, String url, String user, String password) throws SQLException {
super();
// TODO Auto-generated constructor stub
try {
Class.forName(driverClassName).newInstance();
if (user == null && password == null) {
connection = DriverManager.getConnection(url);
} else {
connection = DriverManager.getConnection(url, user, password);
}
} catch (InstantiationException e) {
// TODO Auto-generated catch block
throw new SQLException(e);
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
throw new SQLException(e);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
throw new SQLException(e);
}
}
当 url="jdbc:sqlite:/path/to/sqlite/file/userId.db"
, driverClassName="org.sqlite.JDBC"
, 且 (user = password = null
) 时。
我正在使用 sqlitejdbc-v056.jar
。
希望这有所帮助。