我使用的J2EE开发环境是tomcat+eclipse+lomboz
问题一:怎样连接mysql数据库
步骤1:从mysql网站上下载jdbc驱动:
http://dev.mysql.com/downloads/connector/j/3.1.html
把驱动程序mysql-connector-java-3.1.13-bin.jar拷贝到tomcat安装路径/common/lib下
步骤2:在你工程中的META-INF目录下新建context.xml文件,内容为:
<?xml version="1.0" encoding="UTF-8"?>
<Context>
<Resource name="在程序中注册的引用名" auth="Container"
type="javax.sql.DataSource" username="你的数据库用户名" password="你的数据库密码"
driverClassName="com.mysql.jdbc.Driver" url="jdbc:mysql://localhost/建立的数据库名"
maxActive="8" maxIdle="4"/>
</Context>
<Context>
<Resource name="在程序中注册的引用名" auth="Container"
type="javax.sql.DataSource" username="你的数据库用户名" password="你的数据库密码"
driverClassName="com.mysql.jdbc.Driver" url="jdbc:mysql://localhost/建立的数据库名"
maxActive="8" maxIdle="4"/>
</Context>
在你的工程中的web.xml配置文件中写入:
<resource-ref>
<res-ref-name>jdbc/BookDB</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
<res-sharing-scope>Shareable</res-sharing-scope>
</resource-ref>
<res-ref-name>jdbc/BookDB</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
<res-sharing-scope>Shareable</res-sharing-scope>
</resource-ref>
步骤3:在你的java类中建立数据库连接,代码如下:
try
{
Context initCtx = new InitialContext();
Context envCtx = (Context) initCtx.lookup("java:comp/env");
DataSource ds = (DataSource) envCtx.lookup("在程序中注册的引用名");
con = ds.getConnection();
}
catch (Exception ex)
{
throw new Exception("Couldn't open connection to database: "
+ ex.getMessage());
}
{
Context initCtx = new InitialContext();
Context envCtx = (Context) initCtx.lookup("java:comp/env");
DataSource ds = (DataSource) envCtx.lookup("在程序中注册的引用名");
con = ds.getConnection();
}
catch (Exception ex)
{
throw new Exception("Couldn't open connection to database: "
+ ex.getMessage());
}