当前位置:网站首页>JDBC database addition, deletion, query and modification tool class
JDBC database addition, deletion, query and modification tool class
2022-04-23 20:14:00 【Jiugui wine!!!】
package com.jdbc.utils;
/*
Database addition, deletion, query and modification tools
* Database query dataset json It's a tool getRes()
1、 Get database data
2、 Convert the queried data into json Format
3、 take json Data to the front end
*/
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;
import javax.imageio.IIOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.mysql.jdbc.PreparedStatement;
import com.mysql.jdbc.Statement;
import Module.course;
import Module.xs;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
// You can see an obvious difference , One uses { } , One of the outermost uses is [ ]
//JSONObject The data of { } To express
// and JSONArray, As the name suggests, it's from JSONObject Make an array of , use [ { } , { } , ...... , { } ] To express
public class JdbcCRUDUtil {
// Query operation
public static JSONArray getRes(String sql0,HttpServletRequest request, HttpServletResponse response,Object...args) throws ServletException, IOException, SQLException
{
// Object...args Namely object[] args Parameters , It means that the parameters of the method are dynamic , You can write any parameter
request.setCharacterEncoding("UTF-8");
response.setContentType("text/html;Charset=UTF-8");
// PrintWriter out1=response.getWriter();
Connection con1=(Connection) JdbcConUtil.getConnection();
ResultSet rs1=null;
// rs1 The data returned is not the data in the database , It is rs1 It's like a pointer , At this point, point to the first row of data in the database
JSONArray jsonarr1=new JSONArray();
try {
PreparedStatement st1=(PreparedStatement) con1.prepareStatement(sql0);
for(int i=0;i<args.length;i++)
st1.setObject(i+1, args[i]);
// serObject The function of is to SQL Set the value of the variable in the statement , The first parameter is the meaning of the attributes , The second parameter is the value to be set value
rs1=st1.executeQuery();
java.sql.ResultSetMetaData md0= rs1.getMetaData();//getMetaData Get the structure information of the result set , For example, the number of fields ( How many attributes does the index database have )、 Field name ( The name of the attribute in the table ) etc. .
//rs.getMetaData().getColumnCount() Number of fields , That's the number of columns
//rs.getMetaData().getColumnName(i)); Field name , That is, the name of each column
int colno=md0.getColumnCount();// Get the number of columns in the table
while(rs1.next()) // Any query result can be encapsulated into a Json Array
{
JSONObject json1=new JSONObject();
for(int i=1;i<=colno;i++)
{ //Object obj0=rs1.getObject(i);
json1.put(md0.getColumnName(i), rs1.getString(i));
// System.out.println(md0.getColumnName(i)+":"+ rs1.getString(i));
}
jsonarr1.add(json1);
}
// out1.print(jsonarr1);
// use flush() Method , Will force the data output , The cache is empty , Finally, close the read-write stream call close() It's done.
// Avoid that some data may remain in the cache , Cause data loss
// out1.flush();// Empty means , The data stream used to clear the buffer
// out1.close();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace(); }
con1.close();
return jsonarr1;
}
// The insert
/* Servlet Code for :
* String sql0 = "insert into student(sno,sname,born,photo) values(?,?,?,?)";
JdbcCRUDUtil.Insert(sql0, sno0, sname0, sr0, filename);*/
public static Integer Insert(String sql0,Object...args) {
Integer re=0;
Connection con1=(Connection) JdbcConUtil.getConnection();
java.sql.PreparedStatement pst1 = null;
try {
pst1=con1.prepareStatement(sql0);
System.out.println(" The length of the array "+args.length);
for(int i=0;i<args.length;i++) {
System.out.println(i+1+":"+args[i]);
pst1.setObject(i+1, args[i]);// The cycle is sql The parameter setting value in the statement ,args[i] What is saved in the is the data transmitted from the front end
}
re=pst1.executeUpdate();
JdbcConUtil.close(pst1, con1);
} catch (SQLException e) {
e.printStackTrace();
}
return re;
}
/* Servlet Code for :
* xs tempXs=new xs(sno0,sname0,sex0,sr0,filename);
String sql0 = "insert into student(sno,sname,sex,born,photo) values(?,?,?,?,?)";
JdbcCRUDUtil.InsertObject(sql0, tempXs);*/
public static Integer InsertObject(String sql0,xs tempXs) {
Integer re=0;
Connection con1=(Connection) JdbcConUtil.getConnection();
java.sql.PreparedStatement pst1 = null;
try {
pst1=con1.prepareStatement(sql0);
pst1.setString(1, tempXs.getSno());
pst1.setString(2, tempXs.getSname());
pst1.setString(3, tempXs.getSex());
pst1.setObject(4, tempXs.getBorn());
pst1.setString(5, tempXs.getPhoto());
re=pst1.executeUpdate();
JdbcConUtil.close(pst1, con1);
} catch (SQLException e) {
e.printStackTrace();
}
return re;
}
// Parameters : Table name ,sql Field name ,sql value , file name
public static void inserttable(String tablename, String sqlfiestr1,String sqlvalSTR1,String fname1,String tablname1 ) {
if(sqlfiestr1.length()<1||sqlvalSTR1.length()<1) // That means there is no data upload
;
else { // It indicates that there is data upload in the form , In this way, it is necessary to write to the database . The classmates , This laziness The premise of the method is HMTL Controls in the form name It must be the same as the column name of the database table .
String sqlstr1="";
if(fname1==""||fname1.equals(""))// It means that no file has been uploaded
{ // To remove the last comma in the field name string
sqlfiestr1=sqlfiestr1.substring(0,sqlfiestr1.length()-1);
sqlvalSTR1=sqlvalSTR1.substring(0,sqlvalSTR1.length()-1);
sqlstr1="insert into "+tablename+"("+sqlfiestr1+")values("+sqlvalSTR1+")";
}
else // It means that there are documents coming up , File name is not empty . adjustment insert String photo parameters
{ sqlfiestr1=sqlfiestr1+"photo";
int po=fname1.lastIndexOf("\\"); // Keep only the following file names , Don't go ahead
if(po!=-1)// Indicates that the right slash was found \
{ fname1=fname1.substring(po+1);}
sqlvalSTR1=sqlvalSTR1+"'"+fname1+"'";
sqlstr1="insert into "+tablename+"("+sqlfiestr1+")values("+sqlvalSTR1+")";
}
System.out.println(sqlstr1);
Connection con1=(Connection) JdbcConUtil.getConnection();
Statement st1;
try {
st1 = (Statement) con1.createStatement();
st1.execute(sqlstr1);
JdbcConUtil.close(st1, con1);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
版权声明
本文为[Jiugui wine!!!]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204210556006788.html
边栏推荐
- PCL点云处理之基于PCA的几何形状特征计算(五十二)
- Error reported by Azkaban: Azkaban jobExecutor. utils. process. ProcessFailureException: Process exited with code 64
- R语言使用caret包的preProcess函数进行数据预处理:对所有的数据列进行BoxCox变换处理(将非正态分布数据列转换为正态分布数据、不可以处理负数)、设置method参数为BoxCox
- SIGIR'22「微软」CTR估计:利用上下文信息促进特征表征学习
- Why is the hexadecimal printf output of C language sometimes with 0xff and sometimes not
- R language ggplot2 visual facet_wrap, and use the lineheight parameter to customize the height of the facet icon tab (gray label bar)
- 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.
- R language uses timeroc package to calculate the multi time AUC value of survival data under competitive risk, uses Cox model and adds covariates, and R language uses the plotauccurve function of time
- Paper writing 19: the difference between conference papers and journal papers
- 山东大学软件学院项目实训-创新实训-网络安全靶场实验平台(六)
猜你喜欢
程序设计语言基础(2)
Compact CUDA tutorial - CUDA driver API
Mfcc: Mel frequency cepstrum coefficient calculation of perceived frequency and actual frequency conversion
如何在BNB鏈上創建BEP-20通證
An error is reported when sqoop imports data from Mysql to HDFS: sqlexception in nextkeyvalue
PCL点云处理之计算两平面交线(五十一)
php参考手册String(7.2千字)
Comment créer un pass BEP - 20 sur la chaîne BNB
SIGIR'22 "Microsoft" CTR estimation: using context information to promote feature representation learning
Leetcode XOR operation
随机推荐
WordPress插件:WP-China-Yes解决国内访问官网慢的方法
本地调用feign接口报404
C6748 software simulation and hardware test - with detailed FFT hardware measurement time
SIGIR'22「微软」CTR估计:利用上下文信息促进特征表征学习
MySQL数据库 - 数据库和表的基本操作(二)
R language uses econocrats package to create microeconomic or macroeconomic map, visualize indifference function indifference curve, customize calculation intersection, and customize the parameters of
Electron入门教程3 ——进程通信
LeetCode动态规划训练营(1~5天)
数据库查询 - 选课系统
Leetcode XOR operation
使用 WPAD/PAC 和 JScript在win11中进行远程代码执行1
Esp8266 - beginner level Chapter 1
Mysql database - single table query (I)
Redis cache penetration, cache breakdown, cache avalanche
WordPress plug-in: WP CHINA Yes solution to slow domestic access to the official website
Redis installation (centos7 command line installation)
VeraCrypt文件硬盘加密使用教程
如何做产品创新?——产品创新方法论探索一
[text classification cases] (4) RNN and LSTM film evaluation Tendency Classification, with tensorflow complete code attached
山东大学软件学院项目实训-创新实训-网络安全靶场实验平台(八)