JSP MySQL JSP连接MySQL

JSP MySQL JSP连接MySQL
2007-04-13 14:51

1.先装好JDK ex:C:/j2sdk1.4.2

2.再装TomCat     ex:C:/Tomcat 5.0

3.下载 JDBC 驱动 
 http://mysql.easynet.be/Downloads/Connector-J/mysql-connector-java-3.1.14.zip

 下载就直接解压,里面有一个 mysql-connector-java-3.1.14-bin.jar 文件

 在 C:/ 建立一个 mysqlforjdbc 文件夹,将 mysql-connector-java-3.1.14-bin.jar 复制到这个文件夹中.
 再将 mysql-connector-java-3.1.14-bin.jar 复制到 C:/j2sdk1.4.2/lib 中
 再将 mysql-connector-java-3.1.14-bin.jar 复制到 C:/Tomcat 5.0/common/lib 和 C:/Tomcat 5.0/shared/lib 中

4.设置环境变量

5.执行代码,输出结果
在 C:/Tomcat 5.0/webapps/ROOT 中新建 test_mysql.jsp 测试文件
<%@ page contentType="text/html; charset=gb2312" %>
<%@ page language="java" %>
<%@ page import="com.mysql.jdbc.Driver" %>
<%@ page import="java.sql.*" %>
<%
//驱动程序名
String driverName="com.mysql.jdbc.Driver";
//数据库用户名
String userName="root";
//密码
String userPasswd="";
//数据库名
String dbName="ex";
//表名
String tableName="post";
//联结字符串
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);
//获得数据结果集合
ResultSetMetaData rmeta = rs.getMetaData();
//确定数据集的列数,亦字段数
int numColumns=rmeta.getColumnCount();
out.print("id");
out.print("| ");
out.print("title");
out.print("| ");
out.print("comment ");
out.print("
");
while(rs.next()) {
out.print(rs.getString(1));
out.print("   |   ");
out.print(rs.getString(2));
out.print("   |   ");
out.print(rs.getString(3));
out.print("
");
}
out.print("
");
out.print("数据库操作成功,恭喜你");
rs.close();
statement.close();
connection.close();
%>

你可能感兴趣的:(JSP MySQL JSP连接MySQL)