您的位置:首页 > 运维架构 > Tomcat

Tomcat添加MySQL数据库配置

2016-02-15 00:00 519 查看
摘要: Tomcat, MySQL

下载MySQL的Connector,下载地址:http://dev.mysql.com/downloads/connector/j/

解压,将其中的mysql-connector-java-*-bin.jar复制到tomcat安装目录的lib目录下

在项目的WebContent\META-INF目录下新建content.xml,内容如下

<Context>
<Resource name="jdbc/名字(随便写,后面要用到)" auth="Container" type="javax.sql.DataSource" maxActive="50" maxIdle="30" maxWait="10000" logAbandoned="true" username="用户名" password="密码" driverClassName="com.mysql.jdbc.Driver" url="jdbc:mysql://localhost:3306/数据库名字?autoReconnect=true"/>
</Context>

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();
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: