JSP连接MySQL数据库及环境配置

1 安装相关软件

Eclipse的安装:网址http://eclipse.org/downloads/  选择Eclipse IDE for Java EE Developers进行安装(如果安装Eclipse Standard则后面需要安装很多插件来实现需要的功能,安装Java EE插件的过程:1.依次点击:Help -> InstallNew Software... -> Add。2.输入:http://download.eclipse.org/releases/indigo。3.选择:Eclipse Java EE DeveloperTools,并进行安装。4.重启 eclipse。

MySQL的安装:网址http://www.mysql.com/downloads/mysql/#downloads 选择相应版本下载即可。 下载JDBC驱动:网址 http://www.mysql.com/downloads/connector/j/需要解压后的mysql-connector-java-***-bin.jar(本文中***表示对应版本号)

Tomcat的安装:网址 http://tomcat.apache.org/download-70.cgi 选择相应版本下载(选择32-bit/64-bit Windows Service Installer版本下载为exe文件,直接安装即可。)下载Tomcat对应的Eclipse插件:网址http://www.eclipsetotale.com/tomcatPlugin.html 下载后解压,解压后的com.sysdeo.eclipse.tomcat_***文件夹放到eclipse的plug目录中。重启Eclipse会看到三个猫形图标,表明安装成功。(如果没有出现这三个图标,那么选择'Window>Customize Perspective...>Commands',并在'Available command groups'中勾选'Tomcat'。)配置tomcat的版本,在Windows-Preferences-Tomcat选择对应版本。配置完毕,应用按钮按下,关闭,然后先从window的服务中停止tomcat的服务,回到eclipse的页面,点那三个图标,下面的console的窗口有反映,然后打开浏览器,输入http://localhost:8080/ ,可以看到tomcat启动了。

 

Eclipse通过JDBC连接MySQL数据库

在Eclipse中导入JDBC的jar包

新建工程-右键单击Workspace中工程名-Build Path-Java Build Path-Libraries-AddExternal JARs-选中对应的jar包即可。

命令行测试(查看MySQL数据库是否可用):

(1)首先进入bin根目录  方法为: cd /d  D:\MySQL\MySQL Server 5.6\bin

(2)连接数据库 mysql –uroot –pjava (mysql –u用户名 –p密码)

(3) 查看全部数据库 show databases;(不要忘记分号)

(4) 使用数据库 use test;

(5) 查看全部的表 show tables;(使用数据库后才能进行操作)

代码测试(查看Eclipse是否连接上MySQL)

import java.sql.*;

public class JDBCMySQL {
	public static Connection getConnection() throws SQLException,
			java.lang.ClassNotFoundException {
		// 第一步:加载MySQL的JDBC的驱动 (加载包中)
		Class.forName("com.mysql.jdbc.Driver");
		// 取得连接的url,能访问MySQL数据库的用户名root,密码java;test为数据库名(通过命令行可查看已有数据库)
		String url = "jdbc:mysql://localhost:3306/test";
		String username = "root";
		String password = "java";
		// 第二步:创建与MySQL数据库的连接类的实例
		Connection con = DriverManager.getConnection(url, username, password);
		return con;
	}

	public static void main(String[] args) {
		try {
			// 第三步:获取连接类实例con,用con创建Statement对象类实例 sql_statement
			Connection con = getConnection();
			Statement sql_statement = con.createStatement();

			/** */
			/************ 对数据库进行相关操作 ************/
			// 如果同名数据库存在,删除
			 sql_statement.executeUpdate("drop table if exists student");
			// 执行了一个sql语句生成了一个名为student的表
			 sql_statement.executeUpdate("create table student (id int not null auto_increment, name varchar(20) not null default 'name', math int not null default 60, primary key (id) ); ");
			// 向表中插入数据
			 sql_statement.executeUpdate("insert student values(1, 'liying', 98)");
			 sql_statement.executeUpdate("insert student values(2, 'jiangshan', 88)");
			 sql_statement.executeUpdate("insert student values(3, 'wangjiawu', 78)");
			 sql_statement.executeUpdate("insert student values(4, 'duchangfeng', 100)");
			
			// 第四步:执行查询,用ResultSet类的对象,返回查询的结果
			String query = "select * from student";
			ResultSet result = sql_statement.executeQuery(query);
			/** */
			/************ 对数据库进行相关操作 ************/

			System.out.println("Student表中的数据如下:");
			System.out.println("------------------------");
			System.out.println("学号" + " " + "姓名" + " " + "数据成绩 ");
			System.out.println("------------------------");
			// 对获得的查询结果进行处理,对Result类的对象进行操作
			while (result.next()) {
				int number = result.getInt("id");
				String name = result.getString("name");
				String mathScore = result.getString("math");
				// 取得数据库中的数据
				System.out.println(" " + number + " " + name + " " + mathScore);
			}

			// 关闭连接和声明
			sql_statement.close();
			con.close();

		} catch (java.lang.ClassNotFoundException e) {
			// 加载JDBC错误,所要用的驱动没有找到
			System.err.print("ClassNotFoundException");
			// 其他错误
			System.err.println(e.getMessage());
		} catch (SQLException ex) {
			// 显示数据库连接错误或查询错误
			System.err.println("SQLException: " + ex.getMessage());
		}

	}
}

 

使用以上代码需要修改的地方:

//MySQL 数据库的用户名 , 密码 , 数据库名

		String url = "jdbc:mysql://localhost:3306/test";
		String username = "root";
		String password = "java";
以及具体基本表中的所要查询的字段名(可通过命令行查看数据库中表的内容):
                int number = result.getInt("id");
		String name = result.getString("name");
		String mathScore = result.getString("math");

 

3 Tomcat的配置

测试Eclipse的连接(参考http://blog.sina.com.cn/s/blog_6714fba701018isj.html)

新建一个工程(在Web中选择Dynamic Web Project)-配置Target Runtime-选择相应版本-finish。

在Workspce的相应工程中,找到WebContent文件夹,右键新建一个JSP File,写入测试代码:

<body>
<%
out.println(" Hello Tomcat! ");
%>
</center>
Time is 
<%=new java.util.Date()%>
</center>
</body>

如果出现Several ports (8005, 8080, 8009) required by Tomcatv7.0 Server at localhost are already in use错误,就关掉javaw.exe,再运行代码即可。

 

4 JSP连接MySQL数据库

用mysql驱动把mysql与tomcat的连接起来。把mysql驱动包(不用解压)放到Tomcat安装目录中lib文件夹下即可。
测试代码:(在步骤3中创建的工程中测试即可,数据库还是步骤2中的数据库)

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@ page import="com.mysql.jdbc.Driver" %>
<%@ page import="java.sql.*" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>

<%
//驱动程序名
String driverName="com.mysql.jdbc.Driver";
//数据库用户名
String userName="root";
//密码
String userPasswd="java";
//数据库名
String dbName="test";
//表名
String tableName="student";
//联结字符串
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("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("Congratulations!");
rs.close();
statement.close();
connection.close();
%>

</body>
</html>

运行即可在Web Brower中看到数据库中内容。

大功告成!


  • 7
    点赞
  • 25
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值