下载MySQL的Connector,下载地址:http://dev.mysql.com/downloads/connector/j/
解压,将其中的mysql-connector-java-*-bin.jar复制到tomcat安装目录的lib目录下
在项目的WebContent\META-INF目录下新建content.xml,内容如下
Java使用数据库的代码
Properties properties = new Properties();
properties.put(javax.naming.Context.PROVIDER_URL, "jnp:///");
properties.put(javax.naming.Context.INITIAL_CONTEXT_FACTORY, "org.apache.naming.java.javaURLContextFactory");
try
{
InitialContext jndiContext = new InitialContext(properties);
DataSource datasource = (DataSource) jndiContext.lookup("java:comp/env/jdbc/数据源名称(上面配置的)");
Connection connection = null;
try
{
connection = datasource.getConnection();
//用connection做一些事情
}
catch (SQLException e)
{
e.printStackTrace();
}
}
catch (NamingException e)
{
e.printStackTrace();
}