您的位置:首页 > 数据库 > MySQL

JSP 连接 MySQL 数据库的例子

2008-12-17 21:58 459 查看
一:数据库
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.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: