当前位置:网站首页>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
边栏推荐
- NC basic usage 3
- IIS data conversion problem: 16bit to 24bit
- 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.
- Leetcode dynamic planning training camp (1-5 days)
- nc基础用法
- 论文写作 19: 会议论文与期刊论文的区别
- nc基础用法3
- 山东大学软件学院项目实训-创新实训-网络安全靶场实验平台(五)
- [target tracking] pedestrian attitude recognition based on frame difference method combined with Kalman filter, with matlab code
- 基于pytorch搭建GoogleNet神经网络用于花类识别
猜你喜欢

WordPress plug-in: WP CHINA Yes solution to slow domestic access to the official website

Software College of Shandong University Project Training - Innovation Training - network security shooting range experimental platform (8)

Five minutes to show you what JWT is

考研英语唐叔的语法课笔记

MySQL advanced lock - overview of MySQL locks and classification of MySQL locks: global lock (data backup), table level lock (table shared read lock, table exclusive write lock, metadata lock and inte

selenium. common. exceptions. WebDriverException: Message: ‘chromedriver‘ executable needs to be in PAT

The textarea cursor cannot be controlled by the keyboard due to antd dropdown + modal + textarea

Redis cache penetration, cache breakdown, cache avalanche

SIGIR'22「微软」CTR估计:利用上下文信息促进特征表征学习

php参考手册String(7.2千字)
随机推荐
Kubernetes getting started to proficient - install openelb on kubernetes
VeraCrypt文件硬盘加密使用教程
MySQL数据库 - 连接查询
redis 分布式锁
PCL点云处理之直线与平面的交点计算(五十三)
R language ggplot2 visualization: ggplot2 visualizes the scatter diagram and uses geom_ mark_ The ellipse function adds ellipses around data points of data clusters or data groups for annotation
nc基础用法3
Cadence OrCAD capture batch change component packaging function introduction graphic tutorial and video demonstration
Mysql database backup scheme
Remote code execution in Win 11 using wpad / PAC and JScript 3
php参考手册String(7.2千字)
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
Mysql database - single table query (I)
MySQL advanced lock - overview of MySQL locks and classification of MySQL locks: global lock (data backup), table level lock (table shared read lock, table exclusive write lock, metadata lock and inte
NC basic usage 1
Vericrypt file hard disk encryption tutorial
Kibana reports an error server is not ready yet. Possible causes
Electron入门教程4 —— 切换应用的主题
aqs的学习
selenium.common.exceptions.WebDriverException: Message: ‘chromedriver‘ executable needs to be in PAT