首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >用JSP访问数据库

问用JSP访问数据库
EN

Stack Overflow用户
提问于 2013-06-27 17:15:25
回答 3查看 5.5K关注 0票数 1

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

代码语言:javascript
复制
    <%@ 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页面是

代码语言:javascript
复制
   <%@ 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

我哪里错了?

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2013-06-27 17:58:45

使用这个

代码语言:javascript
复制
<%@ 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>
票数 0
EN

Stack Overflow用户

发布于 2013-06-27 17:19:49

Jsp用于前端,因此请避免在此处编写数据库代码

适用于您的解决方案

添加jar文件download

代码语言:javascript
复制
mysqlconnecter.jar
票数 1
EN

Stack Overflow用户

发布于 2014-01-26 02:05:43

朋友,在下载mysqlconnector之后,您应该提供到jdk的mysqlconnector路径。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/17339212

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档