servlet读MySQL数据库的问题

fire_fly0 2015-08-13 08:32:54
就是用servlet读MySQL数据库的一个单表


//先建一个连数据库的Connection
package link;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

import javax.naming.NamingException;

public class DB {
private String driverName="com.mysql.jdbc.Driver";
private String user="root";
private String password="PASSWORD";
private String url="jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=gbk";
public String getDriverName() {
return driverName;
}
public void setDriverName(String driverName) {
this.driverName = driverName;
}
public String getUser() {
return user;
}
public void setUser(String user) {
this.user = user;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public Connection getConnection(){
try{
Class.forName(driverName);
return DriverManager.getConnection(url,user,password);
}catch(Exception e){
e.printStackTrace();
return null;
}
}


}
**************************************************************************************************************************************
//读数据库里的数据
package link;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class inquiremysql extends HttpServlet {

/**
* Constructor of the object.
*/
public inquiremysql() {
super();
}

/**
* Destruction of the servlet. <br>
*/
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
}

/**
* The doGet method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to get.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

response.setContentType("text/html;charset=utf-8");
PrintWriter out = response.getWriter();

out.println("<HTML>");
out.println(" <HEAD><TITLE>A Servlet</TITLE></HEAD>");
out.println(" <BODY>");
out.print("<table>");
out.print("<tr>");
out.print("<th>学号</th>");
out.print("<th>姓名</th>");
out.print("<th>年龄</th>");
out.print("<th>性别</th>");
out.print("<th>成绩</th>");
out.print("</tr>");
DB conn=new DB();
String sql="select * from stu";
Statement stmt=(Statement) conn.getConnection();

try {
ResultSet rs=stmt.executeQuery(sql);

if(rs.next()){
out.print("<td>"+(String)rs.getString("sId")+"</td>");
out.print("<td>"+(String)rs.getString("sName")+"</td>");
out.print("<td>"+(String)rs.getString("sAge")+"</td>");
out.print("<td>"+(String)rs.getString("sSex")+"</td>");
out.print("<td>"+(String)rs.getString("sScore")+"</td>");

//response.sendRedirect("look.jsp");
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
out.print("</tr>");
out.print("</table>");
out.println(" </BODY>");
out.println("</HTML>");
out.flush();
out.close();
}

/**
* The doPost method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to post.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

doGet(request,response);
}

/**
* Initialization of the servlet. <br>
*
* @throws ServletException if an error occurs
*/
public void init() throws ServletException {
// Put your code here
}

}
**************************************************************************************************************************************
//index.jsp
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">

<title>servlet连数据库</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>

<body>

<a href="link/inquiremysql">点击链接</a>
</body>
</html>
**************************************************************************************************************************************///web.xml,这里面配置了别的servlet在上面的代码里没用到就没贴出来
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<servlet>
<description>This is the description of my J2EE component</description>
<display-name>This is the display name of my J2EE component</display-name>
<servlet-name>inquiremysql</servlet-name>
<servlet-class>link.inquiremysql</servlet-class>
</servlet>
<servlet>
<description>This is the description of my J2EE component</description>
<display-name>This is the display name of my J2EE component</display-name>
<servlet-name>myservlet</servlet-name>
<servlet-class>servlet.myservlet</servlet-class>
</servlet>


<servlet-mapping>
<servlet-name>inquiremysql</servlet-name>
<url-pattern>/servlet/inquiremysql</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>myservlet</servlet-name>
<url-pattern>/servlet/myservlet</url-pattern>
</servlet-mapping>

<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
...全文
253 19 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
19 条回复
切换为时间正序
请发表友善的回复…
发表回复
  • 打赏
  • 举报
回复
不要在getConnection里面用forName加载驱动,驱动放在static静态代码块里面加载一次就行了,你这么写,每次获取链接都会加载一次驱动。
ITjavaman 2015-08-17
  • 打赏
  • 举报
回复
同16楼,我觉得你的配置有问题,你在CMD先检查你能不能连接上数据库吧
冰心的小屋 2015-08-15
  • 打赏
  • 举报
回复
先定位错误的原因吧,是数据库还是Java, 客户端下载个navicat for mysql 或者用命令行连接验证数据库是否有问题 数据库没有问题,看看你Java项目打包的 WEB-INFO下的lib目录是否有 jdbc的包
forDream_ 2015-08-15
  • 打赏
  • 举报
回复
查看驱动包版本,连接字符串,连接账号密码等等是否正确,原因是
DriverManager.getConnection(url,user,password);
没有获取到数据库的连接。
fire_fly0 2015-08-15
  • 打赏
  • 举报
回复
驱动包加进去了呀 而且我也把那两句加到try下面去了啊,不行啊。 servlet不能用会不会跟我的jdk的配置有关,虽然以前用JSP能连上数据库,我的cmd一直不能用。 我跟你们看一下我的jdk配置哈 classpath .;%JAVA-HOME%\lib;%JAVA-HOME%\lib\tools.jar;%catalina_home%\common\lib\servlet.jar JAVA_HOME D:\Program Files\Java\jdk1.8.0_25 path %JAVA-HOME%\bin;%JAVA-HOME%\jre\bin;%tomcat_home%\bin;%MYSQL_HOME%\bin;C:\Program Files\MySQL\MySQL Fabric 1.5.3 & MySQL Utilities 1.5.3 1.5\;C:\Program Files\MySQL\MySQL Fabric 1.5.3 & MySQL Utilities 1.5.3 1.5\Doctrine extensions for PHP
ITjavaman 2015-08-14
  • 打赏
  • 举报
回复
如果说还出错,那就是你MYSQL的用户密码出错
ITjavaman 2015-08-14
  • 打赏
  • 举报
回复
另外你MySQL的驱动包加进去了吧
ITjavaman 2015-08-14
  • 打赏
  • 举报
回复
我本地测试成功,Statement stmt=conn.getConnection().createStatement();是添加到你下面那个Try里面去 也就是try { Statement stmt=conn.getConnection().createStatement(); ResultSet rs=stmt.executeQuery(sql);
nicholasbobo 2015-08-14
  • 打赏
  • 举报
回复
引用 7 楼 fire_fly0 的回复:
出错的64行是这一句 Statement stmt=(Statement) conn.getConnection(); 我把这一句: DB conn=new DB(); String sql="select * from stu"; Statement stmt=(Statement) conn.getConnection(); 改成了这样: DB conn=new DB(); String sql="select * from stu"; Connection con=conn.getConnection(); Statement stmt=con.createStatement(); 出错的那一行就变成了: Statement stmt=con.createStatement(); 我用 MyEclipse debug 找不到con的值
先不论你这个conn.getConnection()为什么为空,它返回的是Connection,你怎么将它强制转换为Statement
nicholasbobo 2015-08-14
  • 打赏
  • 举报
回复
那证明conn为空啊,没有获取到数据库的连接
fire_fly0 2015-08-14
  • 打赏
  • 举报
回复
Statement stmt=(Statement) conn.getConnection()改为Statement stmt=conn.getConnection().createStatement();也添到太容易里面去了,还是出一样的错
fire_fly0 2015-08-14
  • 打赏
  • 举报
回复
出错的64行是这一句 Statement stmt=(Statement) conn.getConnection();

我把这一句:
DB conn=new DB();
String sql="select * from stu";
Statement stmt=(Statement) conn.getConnection();
改成了这样:
DB conn=new DB();
String sql="select * from stu";
Connection con=conn.getConnection();
Statement stmt=con.createStatement();
出错的那一行就变成了: Statement stmt=con.createStatement();
我用 MyEclipse debug 找不到con的值

ITjavaman 2015-08-14
  • 打赏
  • 举报
回复
看错了以为你用表单提交的,你试试在servlet文件里的 Statement stmt=(Statement) conn.getConnection()改为Statement stmt=conn.getConnection().createStatement(); 然后加到try里面去
ITjavaman 2015-08-14
  • 打赏
  • 举报
回复
XML配置文件那里 <servlet-name>inquiremysql</servlet-name>下面应该是同一个名字inquiremysql
nicholasbobo 2015-08-14
  • 打赏
  • 举报
回复
引用 1 楼 fire_fly0 的回复:
忘了贴错误了 HTTP Status 500 - type Exception report message description The server encountered an internal error () that prevented it from fulfilling this request. exception java.lang.NullPointerException link.inquiremysql.doGet(inquiremysql.java:64) javax.servlet.http.HttpServlet.service(HttpServlet.java:690) javax.servlet.http.HttpServlet.service(HttpServlet.java:803) note The full stack trace of the root cause is available in the Apache Tomcat/6.0.13 logs. Apache Tomcat/6.0.13
出错的64行是什么代码
「已注销」 2015-08-13
  • 打赏
  • 举报
回复
看一下连接驱动
姜小白- 2015-08-13
  • 打赏
  • 举报
回复
DB conn=new DB(); String sql="select * from stu"; Statement stmt=(Statement) conn.getConnection(); debug下,是否conn 为null,数据库没有连上
fire_fly0 2015-08-13
  • 打赏
  • 举报
回复
忘了贴错误了 HTTP Status 500 - type Exception report message description The server encountered an internal error () that prevented it from fulfilling this request. exception java.lang.NullPointerException link.inquiremysql.doGet(inquiremysql.java:64) javax.servlet.http.HttpServlet.service(HttpServlet.java:690) javax.servlet.http.HttpServlet.service(HttpServlet.java:803) note The full stack trace of the root cause is available in the Apache Tomcat/6.0.13 logs. Apache Tomcat/6.0.13

81,122

社区成员

发帖
与我相关
我的任务
社区描述
Java Web 开发
社区管理员
  • Web 开发社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧