使用JSP访问数据库

时间:2013-06-27 09:15:25

标签: mysql jsp

我正在学习JSP,我想使用JSP在mysql中创建一个表。我有以下代码。

    <%@ page contentType="text/html;charset=UTF-8" %>
    <%@ page errorPage="error.jsp" %>
    <%@ page import="java.sql.*" %>

    <html>
    <head>
    <title>MySQL Database creation</title>
    <style>
      { font-size: 12px; font-family: Verdana }
    </style>
    </head>
    <body>

    <h2>Creation of a books database</h2>

    <jsp:declaration>

    Statement stmt;
    Connection con;
    String url = "jdbc:mysql://localhost:3306/";

    </jsp:declaration>

    <jsp:scriptlet><![CDATA[

    Class.forName("com.mysql.jdbc.Driver");
    con = DriverManager.getConnection(url, "root", ""); 

    stmt = con.createStatement();
    stmt.executeUpdate("CREATE DATABASE books");
    con.close();

    ]]></jsp:scriptlet>

    </body>
    </html>

我的error.jsp页面是

   <%@ page contentType="text/html" pageEncoding="UTF-8"%>
   <%@ page isErrorPage="true" %>

   <html>
   <head>
   <title>Error page</title>
   <style>
     { font-size: 12px; font-family: Verdana }
   </style>
   </head>
   <body>
   <h2>Error occured!</h2>
   <p>Message 
   <jsp:expression> 
        exception.getMessage() 
   </jsp:expression>
   </p>

   </body>
   </html>

当我运行它时,它会被重定向到错误页面并获得如下输出:

发生错误! 消息com.mysql.jdbc.Driver

我哪里错了?

3 个答案:

答案 0 :(得分:1)

前端的Jsp所以请避免使用数据库代码

为您解决方案

添加jar文件download

mysqlconnecter.jar

答案 1 :(得分:0)

使用此

<%@ page contentType="text/html;charset=UTF-8" %>
<%@ page errorPage="error.jsp" %>
<%@ page import="java.sql.*" %>

<html>
<head>
<title>MySQL Database creation</title>
<style>
  { font-size: 12px; font-family: Verdana }
</style>
</head>
<body>

<h2>Creation of a books database</h2>

<jsp:declaration>

Statement stmt;
Connection con;
String url = "jdbc:mysql://localhost:3306/your database name";

</jsp:declaration>

<jsp:scriptlet><![CDATA[

Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection(url, "root", ""); 

stmt = con.createStatement();
stmt.executeUpdate("CREATE TABLE `test`.`sample` (`id` TINYINT UNSIGNED), `name` VARCHAR (50)");
con.close();

]]></jsp:scriptlet>

答案 2 :(得分:0)

下载你的mysqlconnector后,你应该提供jdk的mysqlconnector路径。