JSP 連接 MySQL 數據庫的例子

一:數據庫
1. 正確install  mysql
2. mysql -h localhost -u root -p
3. create database shujuku;
4. grant all privileges on shujuku.* to test@localhost identified by "12345";
5. use shujuku;
6. create table biao (id int(8) primary key, name varchar (32));
7. insert into biao value(1,'vingo');
8. download mysql jdbc driver and copy the 'mysql-connector-java-5.1.7-bin.jar' to tomcat lib directory.

二: JSP part
 <%@ page language="java" %>
 <%@ page import="com.mysql.jdbc.Driver" %>
 <%@ page import="java.sql.*" %>

 <%
 String driverName = "com.mysql.jdbc.Driver";
 String userName="test";
 String userPasswd="12345";
 String dbName = "shujuku";
 String tableName = "biao";
 String url="jdbc:mysql://localhost/" + dbName + "?user=" + userName + "&password=" +userPasswd ;


 Class.forName("com.mysql.jdbc.Driver").newInstance();
 Connection connection = DriverManager.getConnection(url);
 Statement statement = connection.createStatement();
 String sql = "SELECT * FROM " + tableName ;
 ResultSet rs = statement.executeQuery(sql);
 // get the result set
 ResultSetMetaData rsmeta = rs.getMetaData();

 int numColums = rsmeta.getColumnCount();

 out.print("id");
 out.print("|");
 out.print("name");
 out.print("<br>") ;
 while(rs.next()) {
 out.print(rs.getString(1) + " ") ;
 out.print("|");
 out.print(rs.getString(2));
out.print("<br>");
}

out.print("<br>");
out.print("database query successfully ... congratulation ... ");
rs.close();
statement.close();
connection.close();
%>

三:Don't forget to restart tomcat, it should reload all library.

發佈了62 篇原創文章 · 獲贊 0 · 訪問量 9萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章