Servlet 连接mysql数据库
时间:2021-07-01 10:21:17
帮助过:3人阅读
package com.servlet.datalink;
2
3 import java.io.IOException;
4 import java.io.PrintWriter;
5 import java.sql.Connection;
6 import java.sql.DriverManager;
7 import java.sql.ResultSet;
8 import java.sql.Statement;
9
10 import javax.servlet.ServletException;
11 import javax.servlet.http.HttpServlet;
12 import javax.servlet.http.HttpServletRequest;
13 import javax.servlet.http.HttpServletResponse;
14
15 public class Datalink
extends HttpServlet {
16
17 public void doGet(HttpServletRequest request, HttpServletResponse response)
18
19 throws ServletException, IOException {
20 // 设置上下文类型
21 response.setContentType("text/html;charset=utf-8"
);
22 // 设置统一文档编码
23 request.setCharacterEncoding("UTF-8"
);
24 PrintWriter out =
response.getWriter();
25 // 创建相应变量并赋值为null
26 Connection conn =
null;
27 Statement stmt =
null;
28 ResultSet rs =
null;
29
30 // 通过异常处理操作
31 try{
32 // 加载mysql数据库驱动
33 Class.forName("com.mysql.jdbc.Driver"
);
34 // 连接到数据库
35 conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/jifang", "root", "admin123456"
);
36 // 创建连接状态
37 stmt =
conn.createStatement();
38 // 对数据库进行操作
39 rs = stmt.executeQuery("select * from user"
);
40 // 输出html信息
41 out.println("<html><head><title>读取数据库信息</title></head><body></body></html>"
);
42 // 利用while循环将数据库中的信息输出
43 while(rs.next()) {
44 out.println(rs.getString("id") + "<br/>"
);
45 out.println(rs.getString("username") + "<br/>"
);
46 out.println(rs.getString("password") + "<br/>"
);
47 }
48 }
catch(Exception e) {
49 e.printStackTrace();
50 }
finally{
51 // 关闭数据源
52 }
53
54 }
55 public void doPost(HttpServletRequest request, HttpServletResponse response)
56 throws ServletException, IOException {
57 this.doGet(request, response);
58 }
59
60 }
四、在tomcat中发布该项目,并利用浏览器进行测试
1)在myeclipse中发布该项目
2)在浏览器中输入对应的URL 路径,显示结果如下
注:这篇文章为本人学习经验,以上操作皆可执行。
Servlet 连接mysql数据库
标签: