当前位置:网站首页>JDBC tool class jdbcconutil gets the connection to the database
JDBC tool class jdbcconutil gets the connection to the database
2022-04-23 20:13:00 【Jiugui wine!!!】
One 、JDBC Tool class for connecting to database
package com.jdbc.utils;
/* Connect to database tool
1、 Registration drive
2、 Connect to database
3、 Close the connection
*/
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
public class JdbcConUtil {
private static String driver;
private static String url=null;
private static String username=null;
private static String password=null;
// These are all to be used by the whole website in the future , All static variables or static code blocks , Once loaded , Global use
private static Properties pro=new Properties(); // Ready to read the configuration file , Creating configuration objects
static {
FileInputStream is=null;
try {
// is=new FileInputStream(new File("D:\\【1】 School professional courses \\ Junior year \\Web Back end development technology \\workspace\\Jdbc\\src\\com\\jdbc\\utils\\jdbc.properties"));
is=new FileInputStream(new File("jdbc.properties"));
// is=class.getResourceAsStream(new File("jdbc.properties"));
}
catch (FileNotFoundException e) { System.out.println(e.toString()); e.printStackTrace();
// TODO: handle exception
}
try { pro.load(is); // Load files from disk , It should be set according to the specific folder where your configuration file is stored , If you're confused, use the absolute path
}
catch (IOException e) {System.out.println(e.toString()); e.printStackTrace();
// TODO: handle exception
}
// See if you can read the parameters in the file
driver=pro.getProperty("driverClass");
url=pro.getProperty("url");
username=pro.getProperty("username");
password=pro.getProperty("password");
// System.out.println(" from mysql Data obtained from the configuration file "+driver+url+username+password);
try {
Class.forName(driver);// take mysql Driver registered to DriverManager In the middle
}
catch (ClassNotFoundException e) {System.out.println(e.toString());e.printStackTrace();
// TODO: handle exception
} }
// The following is the connection method for external access
public static java.sql.Connection getConnection() { // notes , It can't be mysql Of , yes java.sql Of
java.sql.Connection con1=null; // The parent class is wrong , You can't go back
try {
con1=DriverManager.getConnection(url, username, password);// get mysql The connection of
}
catch (SQLException e) { System.out.println(e.toString());e.printStackTrace();
// TODO: handle exception
}
return con1;
}
// Release resources
public static void close(ResultSet rs,Statement st,Connection conn)// When querying, use
{ if(rs!=null) try {rs.close();}catch (SQLException e) {
// TODO: handle exception
}
if(st!=null) try {st.close();}catch (SQLException e) {
// TODO: handle exception
}
if(conn!=null) try {conn.close();}catch (SQLException e) {
// TODO: handle exception
}
}
public static void close(Statement st,Connection conn) // Use... In non query mode
{ if(st!=null) try {st.close();}catch (SQLException e) {
// TODO: handle exception
}
if(conn!=null) try {conn.close();}catch (SQLException e) {
// TODO: handle exception
}
}
}
Two 、 The configuration file jdbc.properties
username=root
password=123456
url=jdbc:mysql://localhost:3306/xs
driverClass=com.mysql.jdbc.Driver
3、 ... and 、MySQL Driver download of connector
https://pan.baidu.com/s/1ygZ5H9gospSXItc4xqEQag?pwd=6666
Extraction code :6666
Four 、 stay servlet Demonstrate the use of this tool class
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// The unified code is set to utf-8
request.setCharacterEncoding("UTF-8");
response.setContentType("text/html;Charset=UTF-8");
// Get the student number or gender from the front end
String frontdata=request.getParameter("querydata");
System.out.println(" The data to be queried "+frontdata);
String sql0="select * from student";
Connection con1=(Connection) JdbcUtil.getConnection();
ResultSet rs1=null;
Statement st1 = null;
try {
st1 = (Statement) con1.prepareStatement(sql0);
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
rs1=st1.executeQuery(sql0);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// Output data test
try {
while(rs1.next())
// As long as you haven't finished reading . You can also navigate to a certain line . Use for It's OK to cycle
{ // Start outputting student data information
String xs = "";
String xh=rs1.getString(1);
//1=== If you query the student number and the rs The first data pointed to is the same , The query is successful
if (frontdata.equals(xh)) {
for(int i=1;i<=rs1.getMetaData().getColumnCount();i++)
{// A loop outputs a student information System.out.print(rs1.getString(i)+" ");
if(i==5) {
xs=xs+rs1.getString(i)+"*";
}
else {
xs=xs+rs1.getString(i)+"|";
}
}
System.out.println(" The student ID is :"+frontdata+" Of the students ------"+xs);
PrintWriter out1=response.getWriter();
out1.println(xs);
out1.close();
}
String xb=rs1.getString(5);
//2=== If gender equals male, output the student
if(frontdata.equals(xb)) {
for(int i=1;i<=rs1.getMetaData().getColumnCount();i++)
{// A loop outputs a student information System.out.print(rs1.getString(i)+" ");
if(i==5) {
xs=xs+rs1.getString(i)+"*";
}
else {
xs=xs+rs1.getString(i)+"|";
}
}
System.out.println(" The query gender is :"+frontdata+" Of the students -----"+xs);
PrintWriter out1=response.getWriter();
out1.println(xs);
}
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
JdbcUtil.close(rs1,st1,con1);
}
版权声明
本文为[Jiugui wine!!!]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204210556007065.html
边栏推荐
- Inject Autowired fields into ordinary beans
- PCL点云处理之直线与平面的交点计算(五十三)
- Kubernetes introduction to mastery - ktconnect (full name: kubernetes toolkit connect) is a small tool based on kubernetes environment to improve the efficiency of local test joint debugging.
- SRS deployment
- selenium.common.exceptions.WebDriverException: Message: ‘chromedriver‘ executable needs to be in PAT
- filebeat、logstash配置安装
- How to create bep-20 pass on BNB chain
- Electron入门教程4 —— 切换应用的主题
- Remote code execution in Win 11 using wpad / PAC and JScript 1
- The R language uses the timeroc package to calculate the multi time AUC value of survival data without competitive risk, and uses the confint function to calculate the confidence interval value of mul
猜你喜欢
Unity创建超写实三维场景的一般步骤
网络通信基础(局域网、广域网、IP地址、端口号、协议、封装、分用)
山东大学软件学院项目实训-创新实训-网络安全靶场实验平台(五)
程序设计语言基础(2)
@Mapperscan and @ mapper
Project training of Software College of Shandong University - Innovation Training - network security shooting range experimental platform (VII)
CVPR 2022 | QueryDet:使用级联稀疏query加速高分辨率下的小目标检测
STM32基础知识
Openharmony open source developer growth plan, looking for new open source forces that change the world!
Computing the intersection of two planes in PCL point cloud processing (51)
随机推荐
Speex Wiener filter and rewriting of hypergeometric distribution
WordPress plug-in: WP CHINA Yes solution to slow domestic access to the official website
Project training of Software College of Shandong University - Innovation Training - network security shooting range experimental platform (V)
nc基础用法4
2022 - Data Warehouse - [time dimension table] - year, week and holiday
Leetcode XOR operation
山东大学软件学院项目实训-创新实训-网络安全靶场实验平台(五)
Still using listview? Use animatedlist to make list elements move
AQS learning
PCA based geometric feature calculation of PCL point cloud processing (52)
Understanding various team patterns in scrum patterns
php参考手册String(7.2千字)
How about CICC fortune? Is it safe to open an account
Design of library management database system
图书管理数据库系统设计
PCL点云处理之直线与平面的交点计算(五十三)
Kubernetes getting started to proficient - install openelb on kubernetes
The R language uses the timeroc package to calculate the multi time AUC value of survival data without competitive risk, and uses the confint function to calculate the confidence interval value of mul
Wave field Dao new species end up, how does usdd break the situation and stabilize the currency market?
Unity 模型整体更改材质