日期:2014-05-16  浏览次数:20452 次

JSP 连接MySQL数据库

<%@ page contentType="text/html; charset=gb2312"%>
<%@ page language="java"%>
<%@page import="java.sql.*"%>
<%@page import="com.mysql.jdbc.Driver;"%>
<%
?//驱动程序名
?String driverName = "com.mysql.jdbc.Driver";
?//数据库用户名
?String userName = "root";
?//密码
?String userPasswd = "root";
?//数据库名
?String dbName = "mysql";
?//表名
?String tableName = "help_relation";
?//联结字符串
?String url = "jdbc:mysql://localhost/" + dbName + "?user="
???+ userName + "&password=" + userPasswd;

?Class.forName(driverName).newInstance(); // 注册驱动
?Connection connection = DriverManager.getConnection(url); // 建立连接
?Statement statement = connection.createStatement();?? //?? 准备环境执行
?String sql = "SELECT * FROM " + tableName;??? // 建立sql
?ResultSet rs = statement.executeQuery(sql);?? // 执行Sql
?ResultSetMetaData rmeta = rs.getMetaData();//获得数据结果集合
?int numColumns = rmeta.getColumnCount();//确定数据集的列数,亦字段数
?// 输出每一个数据值
?out.print("id");
?out.print("|");
?out.print("num");
?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("数据库操作成功,恭喜你");
?//下面的需要放在catch里面做出判断
?rs.close();
?statement.close();
?connection.close();
%>