最近看到網(wǎng)上不少朋友說(shuō)用JDBC連不上MySQL.有的說(shuō)用IDE做沒(méi)問(wèn)題,但不用IDE部署,自己部署就不成功.想知道為什么?
確實(shí),我記得我那時(shí)也是搞不懂,也很郁悶.其實(shí)問(wèn)題很簡(jiǎn)單,一、要注意web.xml,這可不是看看而已,寫(xiě)配置文件是j2ee的一件大事。二、注意驅(qū)動(dòng)
放置的位置。三、注意項(xiàng)目的結(jié)構(gòu),你不要把jsp文件丟到WEB-INF文件夾下面去了。
tomcat版本: tomcat-5.0.28;
mysql版本: mysql-4.1.13-win32;
廢話少說(shuō), 我來(lái)演示:
1、啟動(dòng)mysql。
2、建數(shù)據(jù)庫(kù),建表,我這都不演示了,請(qǐng)參考相關(guān)文章。
3、在tomcat中的webapps文件中建一個(gè)SQL文件夾,在SQL文件夾中再建一個(gè)WEB-INF文件夾,再在WEB-INF文件夾中建一個(gè)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文件夾中建一個(gè)mysql.jsp。代碼如下:
<%@ page contentType="text/html; charset=gb2312" language="java" import="java.sql.*"%>
<html>
<body>
以下是從MySQL數(shù)據(jù)庫(kù)讀取的數(shù)據(jù):<hr>
<table border=1>
<tr><td>ID</td><td>書(shū)名</td><td>出版社
</td><td>價(jià)格</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>");
}
//關(guān)閉連接、釋放資源
rst.close();
stmt.close();
con.close();
%>
</table>
</body>
</html>
6、將mysql-connector-java-3.1.10-bin.jar放到tomcat\common\lib中。
7、啟動(dòng)tomcat.
8、在瀏覽器中瀏覽:
posted on 2005-10-05 18:06
千山鳥(niǎo)飛絕 閱讀(2887)
評(píng)論(4) 編輯 收藏 所屬分類(lèi):
Web開(kāi)發(fā)