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

JSP连接MySQL数据库
在学习JAVA WEB开发框架之前,eclipse环境的配置和访问数据库的配置,这两个是必修的。

MySQL访问数据库的示例如下,只为学习而用,不为生产用。

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ page language="java" import="java.sql.*" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
// String date = new java.util.Date().toString();
%>

<%
// MySQL连接

Class.forName("com.mysql.jdbc.Driver").newInstance();

Connection conn = null;
conn = DriverManager.getConnection("jdbc:mysql://localhost/myDatabaseName?user=myUserName&password=myPassWord");

Statement stmt = null;
ResultSet rs = null;

stmt = conn.createStatement();

// 数据库中有张表news.
if (stmt.execute("SELECT * FROM news")){
rs = stmt.getResultSet();
}
ResultSetMetaData rmeta = rs.getMetaData();
int numColumns=rmeta.getColumnCount();

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

rs.close();
stmt.close();
conn.close();

%>