从www.mysql.com上下載Connector/J(mysql-connector-java-5.1.0.zip),解壓縮,
拷贝其中的mysql-connector-java-5.1.0-bin.jar到WEB-INF目录下或tomcat的lib下面
建立test.jsp,重新啟動tomcat即可
使用mysql裡test資料庫的login資料表
裡面屬性為pid,pwd
值分別為:
pid pwd
apple apple01
bird bird02
cat cat03
dog dog04
test.jsp
<%@ page contentType="text/html;charset=utf-8"%>
<%@ page import="java.sql.*"%>
<%
try
{
//讀取mysqlDriver驅動程式
Class.forName("org.gjt.mm.mysql.Driver").newInstance();
try
{
//連接mysql資料庫test,帳號:root密碼:mysql
String url="jdbc:mysql://localhost:3306/test";
String id="root";
String pwd="mysql";
Connection conn= DriverManager.getConnection(url,id,pwd);
try
{
//建立statement
Statement stmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);
try
{
//建立SQL查詢
String sql="select * from login";
ResultSet rs = stmt.executeQuery(sql);
//顯示資料
while(rs.next())
{
out.println(rs.getString(1));
out.println(rs.getString(2));
out.println("
");
}
}
catch (Exception ex)
{
out.println("can't read data");
out.println(ex.toString());
}
}
catch (Exception e)
{
out.println("can't create statement");
out.println(e.toString());
}
}
catch(Exception e)
{
out.println("can't content mysql database");
out.println(e.toString());
}
}
catch(Exception e)
{
out.println("can't load mysql driver");
out.println(e.toString());
}
%>
留言列表