直接正题
1.先启动mysql,建立一个表test
2.打开java软件,建立jsp文件mysqlconnect.jsp
,新建好的代码如下
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ 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=UTF-8">
<title>测试数据库连接</title>
</head>
<body>
<%
Connection conn;
Statement statement;
String sql;
ResultSet rs;//建立结果集对象
// URL指向要访问的数据库名blog
String url = "jdbc:mysql://127.0.0.1/blog?serverTimezone=GMT";//不加serverTime时区就报错
// MySQL配置时的用户名
String user = "root";
// Java连接MySQL配置时的密码
String password = "";
try {
// 1 加载驱动程序
Class.forName("com.mysql.jdbc.Driver");
// 2 连接数据库
conn = DriverManager.getConnection(url, user, password);
// 3 用来执行SQL语句
statement = conn.createStatement();
// 要执行的SQL语句
sql = "select * from user";
rs = statement.executeQuery(sql);
String name = null;
String pwd = null;
while (rs.next()) {
name = rs.getString("name");
pwd = rs.getString("pwd");
out.print(name + "\t" + pwd);
out.print("<br/>");
}
rs.close();
conn.close();
} catch (ClassNotFoundException e) {
System.out.print("Sorry,can`t find the Driver!");
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
%>
</body>
</html>
3.将下载好的jar驱动包复制到Tomcat的lib
目录下
4.在mysqlconnect.jsp文件上右键->Bulid Path->Configure Bulid Path..
5.选择librarys的导航,然后选择箭头所指的 Add External jars...
6.选中刚刚复制在tomcat/lib下的jar驱动文件,然后点击打开即可
7.再点击OK
8.还是右击点击Amysqlconnect.jsp,Bulid Path->Add to build path
9.然后就可以运行了