最近看到網上不少朋友說用JDBC連不上MySQL.有的說用IDE做沒問題,但不用IDE部署,自己部署就不成功.想知道為什么?
確實,我記得我那時也是搞不懂,也很郁悶.其實問題很簡單,一、要注意web.xml,這可不是看看而已,寫配置文件是j2ee的一件大事。二、注意驅動
放置的位置。三、注意項目的結構,你不要把jsp文件丟到WEB-INF文件夾下面去了。
tomcat版本: tomcat-5.0.28;
mysql版本: mysql-4.1.13-win32;
廢話少說, 我來演示:
1、啟動mysql。
2、建數據庫,建表,我這都不演示了,請參考相關文章。
3、在tomcat中的webapps文件中建一個SQL文件夾,在SQL文件夾中再建一個WEB-INF文件夾,再在WEB-INF文件夾中建一個classes文件夾和web.xml文件。
4、web.xml代碼如下:
<?xml version="1.0" ?>
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems,
Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd">
<!-- Copyright (c) 2002 by ObjectLearn. All Rights Reserved. -->
<web-app>
<welcome-file-list>
<welcome-file>mysql.jsp</welcome-file>
</welcome-file-list>
</web-app>
5、在SQL文件夾中建一個mysql.jsp。代碼如下:
<%@ page contentType="text/html; charset=gb2312" language="java" import="java.sql.*"%>
<html>
<body>
以下是從MySQL數據庫讀取的數據:<hr>
<table border=1>
<tr><td>ID</td><td>書名</td><td>出版社
</td><td>價格</td></tr>
<%
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection
con=java.sql.DriverManager.getConnection("jdbc:mysql://localhost/BookDB?useUnicode=true&characterEncoding=GBK","t14cwf","cwf");
Statement stmt=con.createStatement();
ResultSet rst=stmt.executeQuery("select * from book");
while(rst.next())
{
out.println("<tr>");
out.println("<td>"+rst.getString("bookId")+"</td>");
out.println("<td>"+rst.getString("bookName")+"</td>");
out.println("<td>"+rst.getString("publisher")+"</td>");
out.println("<td>"+rst.getFloat("price")+"</td>");
out.println("</tr>");
}
//關閉連接、釋放資源
rst.close();
stmt.close();
con.close();
%>
</table>
</body>
</html>
6、將mysql-connector-java-3.1.10-bin.jar放到tomcat\common\lib中。
7、啟動tomcat.
8、在瀏覽器中瀏覽:
posted on 2005-10-05 18:06
千山鳥飛絕 閱讀(2881)
評論(4) 編輯 收藏 所屬分類:
Web開發