標籤:
第一步
在<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());
}
}
}
MyEclipse利用JNDI串連MySQL資料庫