2010年11月22日 星期一

轉貼 jsp 連 mysql

架設好 tomcat 和 mysql 後 , 需要安裝 JDBC Driver 才能讓 tomcat 讀取 mysql,


JDBC driver 安裝擋案可以到 這裡 (http://dev.mysql.com/downloads/connector/j/5.0.html) 下載
下載後 將 mysql-connector-java-5.1.13-bin.jar 這個檔案 放在 tomcat 安裝目錄下的 bin 資料夾裡

當然要重新啟動才會生效





以下是修改後的測試程式,
(從 http://www.roseindia.net/jsp/connect-jsp-mysql.shtml 修改的)
在 mysql 建立 一個 test 資料庫 , 應為這裡沒設密碼 所以帳號密碼就是 "root" ,""






<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">

<%@ page import="java.sql.*" %>
<%@ page import="java.io.*" %>

<html>
<head>
<title>Connection with mysql database</title>
</head>
<body>
<h1>Connection status </h1>
<%
try {
/* Create string of connection url within specified format with machine name,
port number and database name. Here machine name id localhost and
database name is usermaster. */
String connectionURL = "jdbc:mysql://localhost:3306/test";

// declare a connection by using Connection interface
Connection connection = null;

// Load JBBC driver "com.mysql.jdbc.Driver"
Class.forName("com.mysql.jdbc.Driver").newInstance();

/* Create a connection by using getConnection() method that takes parameters of
string type connection url, user name and password to connect to database. */
connection = DriverManager.getConnection(connectionURL, "root", "");

// check weather connection is established or not by isClosed() method
if(!connection.isClosed())
%>
<span ></b>
<%
out.println("Successfully connected to " + "MySQL server using TCP/IP...");
connection.close();
}
catch(Exception ex){
%>
</span>
<span ></b>
<%
out.println("Unable to connect to database.");
}
%>
</span>
</body>
</html>



參考網站
http://wiki.oss.org.tw/index.php/Jsp_database

http://blog.yam.com/carl44/article/14825336

沒有留言: