连接前要下载mysql-connector-java-5.1.13-bin.jar。
如果是使用eclipse将该包置于:
项目->WebContent->WEB-INF->lib下即可。
连接MySQL数据库代码:
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@ page import="java.sql.*" %>
<body>
<%
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://127.0.0.1:3306/mydata";
String user = "root";
String password = "root";
try {
Class.forName(driver);
Connection conn = DriverManager.getConnection(url, user, password);
Statement statement = conn.createStatement();
String sql = "select * from userInfo";
ResultSet rs = statement.executeQuery(sql);
String name = null;
String mima=null;
while (rs.next()) {
out.print("<br>用户名:"+rs.getString("username")+"密码:"+rs.getString("password"));
}
rs.close();
conn.close();
} catch (ClassNotFoundException e) {
System.out.println("Sorry,can`t find the Driver!");
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
%>
</body>