由於考慮到之前網站上很多東西也和 MYSQL 拉上了關係
而且由於伺服器是使用 Resin,而 JSP 也是新手啦,
所以又到網上找了找文章,算是搞懂了,不過很多文章也是舊的
還好,起碼從中得到了一點啟發,再研究了一下,終於完成了,感動
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
| # 首先要安裝 "connector/j" 應該是 connector/java 的意思吧 # 於是可以到 MYSQL 網站中找到 http://www.mysql.com/products/connector/j/
# 在網站中發現官方是建議使用 MySQL Connector/J 5.1 這版本 # 於是冒著好奇心,就使用這個吧,而且網上大多文章也留在 3.1 版本 # 下載時需要使用帳號,於是就註冊了一下,用 Jap 那鏡站下載的.. # 下載回來後,解壓,得到 mysql-connector-java-5.1.6-bin.jar
# 之後再他上載回伺服器,再移到 /usr/local/resin/lib 就可以 mv /home/xxxx/mysql-connector-java-5.1.6-bin.jar /usr/local/resin/lib
# 再查看是否移動了 ls mysql-connector-*
# 之後再修改 Resin 的 config 檔 vi /usr/local/resin/conf/resin.conf
# 再找到 /mysql
# 會發現 <driver type="xxxxxx.mysql.xxxxxx.Driver">
# 別忘了這段設定預設是在 <!-- --> 之內 # 你需將註解刪去再修改成以下樣子 <driver type="com.mysql.jdbc.Driver">
# 之後再重啟一下伺服器 /usr/local/resin/bin/httpd.sh restart
|
測試代碼 在下一頁
測試用代碼(取自網上)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
| <%@ page contentType="text/html;charset=UTF-8" import="java.sql.*" %> <% try{ Class.forName("com.mysql.jdbc.Driver").newInstance(); out.print("成功載入 MySql 驅動!"); }catch(Exception E) { out.print("無法載入 com.mysql.jdbc.Driver "); E.printStackTrace(); }
try { Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/資料庫?user=帳號&password=密碼&useUnicode=true&characterEncoding=UTF-8");
if(!con.isClosed()) out.print("<BR>載入 MySql 資料庫成功!");
PreparedStatement pstmt = con.prepareStatement("select 欄位 FROM 資料表"); ResultSet rs = pstmt.executeQuery();
while(rs.next()){ out.println("<BR>" + rs.getString("欄位")); }
Statement stmt = con.createStatement(); stmt.executeUpdate("INSERT INTO 資料表 (欄位一, 欄位二) VALUES ('值一', '值二')");
stmt.close(); rs.close(); pstmt.close(); con.close(); rs = null; pstmt = null; stmt = null;
}catch(Exception ex) {
out.println("<BR>handle the error"); out.println("<br>====================="); out.println("<BR>SQLException: " + ex.getMessage());
} %>
|