当前位置:网站首页>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
边栏推荐
- 腾讯邱东洋:深度模型推理加速的术与道
- Scrum Patterns之理解各种团队模式
- 波场DAO新物种下场,USDD如何破局稳定币市场?
- An error is reported in the initialization metadata of the dolphin scheduler -- it turns out that there is a special symbol in the password. "$“
- How to do product innovation—— Exploration of product innovation methodology I
- Introduction to electron tutorial 3 - process communication
- PCL点云处理之计算两平面交线(五十一)
- SIGIR'22「微软」CTR估计:利用上下文信息促进特征表征学习
- A simple (redisson based) distributed synchronization tool class encapsulation
- C6748 software simulation and hardware test - with detailed FFT hardware measurement time
猜你喜欢
Azkaban recompile, solve: could not connect to SMTP host: SMTP 163.com, port: 465 [January 10, 2022]
Unity general steps for creating a hyper realistic 3D scene
PCL点云处理之计算两平面交线(五十一)
Leetcode XOR operation
PHP reference manual string (7.2000 words)
Mfcc: Mel frequency cepstrum coefficient calculation of perceived frequency and actual frequency conversion
How to create bep-20 pass on BNB chain
The textarea cursor cannot be controlled by the keyboard due to antd dropdown + modal + textarea
程序设计语言基础(2)
Project training of Software College of Shandong University - Innovation Training - network security shooting range experimental platform (V)
随机推荐
Five minutes to show you what JWT is
antd dropdown + modal + textarea导致的textarea光标不可被键盘控制问题
Still using listview? Use animatedlist to make list elements move
【问题解决】‘ascii‘ codec can‘t encode characters in position xx-xx: ordinal not in range(128)
【文本分类案例】(4) RNN、LSTM 电影评价倾向分类,附TensorFlow完整代码
Error reported by Azkaban: Azkaban jobExecutor. utils. process. ProcessFailureException: Process exited with code 127
Error reported by Azkaban: Azkaban jobExecutor. utils. process. ProcessFailureException: Process exited with code 64
本地调用feign接口报404
Unity创建超写实三维场景的一般步骤
[text classification cases] (4) RNN and LSTM film evaluation Tendency Classification, with tensorflow complete code attached
SRS 的部署
selenium.common.exceptions.WebDriverException: Message: ‘chromedriver‘ executable needs to be in PAT
R语言使用timeROC包计算存在竞争风险情况下的生存资料多时间AUC值、使用cox模型、并添加协变量、R语言使用timeROC包的plotAUCcurve函数可视化多时间生存资料的AUC曲线
How about Bohai futures. Is it safe to open futures accounts?
Shanda Wangan shooting range experimental platform project - personal record (V)
Cadence Orcad Capture 批量更改元件封装功能介绍图文教程及视频演示
Mfcc: Mel frequency cepstrum coefficient calculation of perceived frequency and actual frequency conversion
Is the wechat CICC wealth high-end zone safe? How to open an account for securities
MySQL数据库 - 连接查询
山东大学软件学院项目实训-创新实训-网络安全靶场实验平台(五)