【JAVAEE】JDBC技术运用
本文最后更新于 1740 天前,其中的信息可能已经有所发展或是发生改变。

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/

效果图:

暂无评论

发送评论 编辑评论


				
|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
颜文字
Emoji
小恐龙
花!
上一篇
下一篇