1.创建连接数据库的DbConnect类,定义连接数据库的getDBconnection()方法和释放资源的Close()方法。
com/bean/DbConnec.java
[sourcecode language=”Java” title=”DbConnect.java”]
package com.bean;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class DbConnect {
public static Connection getDBconnection() {
String shujuku = "benzhu";
String url1 ="jdbc:mysql://localhost:3306/"+shujuku;
String uname = "root";
String upwd="123456";
Connection conn=null;
try{
Class.forName("com.mysql.jdbc.Driver");
conn= DriverManager.getConnection(url1, uname, upwd);
System.out.println("哈哈哈哈 连接成功");
}
catch(Exception e){
e.printStackTrace();
}
return conn;
}
public static void Close(Connection conn,Statement stmt,ResultSet rs) {
try{if(rs!=null) rs.close();}catch(Exception e){e.printStackTrace();}
try{if(stmt!=null) stmt.close();}catch(Exception e){e.printStackTrace();}
try{if(conn!=null) conn.close();}catch(Exception e){e.printStackTrace();}
}
}[/sourcecode]
2.创建访问数据库输出用户表信息的servlet类。
conneetion.java
[sourcecode language=”java” title=”conneetion.java”]
package com.servlet;
import java.io.IOException;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.sql.Connection;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.bean.DbConnect;
/**
* Servlet implementation class conneetion
*/
@WebServlet("/conneetion")
public class conneetion extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try{
Connection conn;
conn = DbConnect.getDBconnection();
Statement stmt = conn.createStatement();
String sql="select * from benzhu_user";
ResultSet rs=stmt.executeQuery(sql);
while(rs.next()) {
System.out.println(rs.getInt("user_id")+"\t"+rs.getString("user_name")+"\t"+rs.getString("user_pwd"));
}
DbConnect.Close(conn, stmt, rs);
}
catch(Exception e){
e.printStackTrace();
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}[/sourcecode]
3.eclopse记得导入驱动包,代码按照数据库的实际情况稍微改改就ok。
mysql下载地址:https://benzhu.xyz/index.php/2018/03/27/mysql001/
效果图: