您的位置:首页 > 博客中心 > 数据库 >

MyEclipse利用JNDI连接MySQL数据库

时间:2022-03-14 11:52

第一步
  在<Tomcat安装目录>\conf\server.xml文件夹中找到<GlobalNamingResources>标签并加入一个标签<Resource>,这个标签配置如下:
    <Resource
    name="jdbc/webdb" //数据库名字
    auth="Container"
    type="javax.sql.DataSource" driverClassName="com.mysql.jdbc.Driver" url="jdbc:mysql://localhost:3306/webdb? characterEncoding=utf-8"
    username="root"
    password="1234"
    maxActive="200"
    maxIdle="50"
    maxWait="3000"/>

第二步
  在<Tomcat安装目录>\conf\Catalina\localhost中建立一个 webdemo.xml文件(webdemo和项目名字相同),然后在webdemo.xml文件输入如下内容
    <Context path="/webdemo" docBase="webdemo" debug="0">
    <Resource name="jdbc/webdb" auth="Container"
    type="javax.sql.DataSource"
    driverClassName="com.mysql.jdbc.Driver"
    url="jdbc:mysql://localhost:3306/webdb?characterEncoding=UTF-8"
    username="root"
    password="1234"
    maxActive="200"
    maxIdle="50"
    maxWait="3000"/>
    </Context>

第三步
  在WEN-INF文件夹中的lib文件夹中添加mysql-connector- java-5.1.18-bin.jar架包

第四步
  在项目中的web.xml中添加如下代码
    <servlet>
    <servlet-name>ViewDictionary</servlet-name>
    <servlet-class>ViewDictionary</servlet-class>
    </servlet>
    <servlet-mapping>
    <servlet-name>ViewDictionary</servlet-name>
    <url-pattern>/servlet/ViewDictionary</url-pattern>
    </servlet-mapping>
  注:ViewDictionary是需要运行的servlet的类名

第五步

  在ViewDictionary类中测试,代码如下  

public class ViewDictionary extends HttpServlet
{

public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try
{
javax.naming.Context ctx = new javax.naming.InitialContext();
// 根据webdb数据源获得DataSource对象
javax.sql.DataSource ds = (javax.sql.DataSource) ctx
.lookup("java:/comp/env/jdbc/webdb");
Connection conn = ds.getConnection();
// 执行SQL语句
PreparedStatement pstmt = conn
.prepareStatement("SELECT * FROM t_dictionary");
ResultSet rs = pstmt.executeQuery();
StringBuilder table = new StringBuilder();
table.append("<table border=‘1‘>");
table.append("<tr><td>书名</td><td>价格</td></tr>");
while (rs.next()) // 生成查询结果
{
table.append("<tr><td>" + rs.getString("english") + "</td><td>");
table.append(rs.getString("chinese") + "</td></tr>");
}
table.append("</table>");
out.println(table.toString()); // 输出查询结果

pstmt.close(); // 关闭PreparedStatement对象
}
catch (Exception e)
{
out.println(e.getMessage());
}
}

}

本类排行

今日推荐

热门手游