[基礎]JSP與MYSQL連線
此段語法用於測試是否連線,並SELECT出DB的時間。
<%@page import="java.sql.DriverManager"%>
<%@page import="java.sql.ResultSet"%>
<%@page import="java.sql.Connection"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<%
//資料庫連線資訊編碼方式為utf-8
String url = "jdbc:mysql://localhost:3306/testdb?characterEncoding=utf8&useUnicode=true";
//帳號
String account = "account";
//密碼
String pass = "passs";
//連線
Connection con = null;
//查詢結果
ResultSet rs = null;
//sql
String sql = "";
%>
<%
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection(url,account,pass);
sql = "SELECT NOW() FROM DUAL";
rs = con.createStatement().executeQuery(sql);
while(rs.next()){
out.print( rs.getString(1) );
}
} catch (Exception ex) {
out.print(ex.toString());
} finally {
if (con != null) {
con.close();
}
}
%>
<%@page import="java.sql.DriverManager"%>
<%@page import="java.sql.ResultSet"%>
<%@page import="java.sql.Connection"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<%
//資料庫連線資訊編碼方式為utf-8
String url = "jdbc:mysql://localhost:3306/testdb?characterEncoding=utf8&useUnicode=true";
//帳號
String account = "account";
//密碼
String pass = "passs";
//連線
Connection con = null;
//查詢結果
ResultSet rs = null;
//sql
String sql = "";
%>
<%
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection(url,account,pass);
sql = "SELECT NOW() FROM DUAL";
rs = con.createStatement().executeQuery(sql);
while(rs.next()){
out.print( rs.getString(1) );
}
} catch (Exception ex) {
out.print(ex.toString());
} finally {
if (con != null) {
con.close();
}
}
%>
留言
張貼留言