package com.io;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class My
*/
@WebServlet("/My")
public class My extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Statement stmt=null;
Connection conn=null;
// JDBC driver name and database URL
final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
final String DB_URL = "jdbc:mysql://localhost:3306/testdb";
// Database credentials
final String USER = "root";
final String PASS = "root";
// Set response content type
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String title = "Database Result";
String docType =
"<!doctype html public \"-//w3c//dtd html 4.0 " +
"transitional//en\">\n";
out.println(docType +
"<html>\n" +
"<head><title>" + title + "</title></head>\n" +
"<body bgcolor=\"#f0f0f0\">\n" +
"<h1 align=\"center\">" + title + "</h1>\n");
try{
// Register JDBC driver
//Class.forName("com.mysql.jdbc.Driver");
// Open a connection
conn = DriverManager.getConnection(DB_URL,USER,PASS);
// Execute SQL query
stmt = conn.createStatement();
String sql;
sql = "select * from products";
ResultSet rs = stmt.executeQuery(sql);
// Extract data from result set
while(rs.next())
{
//Retrieve by column name
String id1 = rs.getString("id");
String name1 = rs.getString("name");
String description1 = rs.getString("description");
float price1 = rs.getFloat("price");
//Display values
out.println("ID: " + id1 + "<br>");
out.println(", NAME: " + name1 + "<br>");
out.println(", DESCRIPTION: " + description1 + "<br>");
out.println(", PRICE: " + price1 + "<br>");
}
out.println("</body></html>");
// Clean-up environment
rs.close();
stmt.close();
conn.close();
}
catch(SQLException se){
//Handle errors for JDBC
se.printStackTrace();
}
catch(Exception e){
//Handle errors for Class.forName
e.printStackTrace();
}
finally{
//finally block used to close resources
try
{
if(stmt!=null)
stmt.close();
}
catch(SQLException se2){
}// nothing we can do
try{
if(conn!=null)
conn.close();
}
catch(SQLException se){
se.printStackTrace();
}//end finally try
} //end try
}
}
大家好我在尝试从Mysql数据库中检索值时遇到了问题。我使用Tomcat我已经通过构建路径插入了mysql jar文件,但同样的问题仍然存在。求助。 嗨伙计们,我试图从Mysql数据库中检索值时被击中。我使用Tomcat我已经通过构建路径插入了mysql jar文件,但同样的问题存在。请帮忙。
答案 0 :(得分:1)
尝试将jar直接复制到$ tomcat_path / lib文件夹,而不是添加到构建路径。然后重新启动tomcat并再试一次。
答案 1 :(得分:0)
确保添加了 mysql-connector-java-5.1.x-bin.jar 而不是mysql-connector-java-5.1.x.jar。试试这个。
答案 2 :(得分:0)