当前位置:网站首页>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
边栏推荐
- Kubernetes getting started to proficient - install openelb on kubernetes
- Cadence Orcad Capture CIS更换元器件之Link Database 功能介绍图文教程及视频演示
- Unity创建超写实三维场景的一般步骤
- A simple (redisson based) distributed synchronization tool class encapsulation
- Unity general steps for creating a hyper realistic 3D scene
- Electron入门教程3 ——进程通信
- Mysql database and table building: the difference between utf8 and utf8mb4
- Wave field Dao new species end up, how does usdd break the situation and stabilize the currency market?
- 論文寫作 19: 會議論文與期刊論文的區別
- Shanda Wangan shooting range experimental platform project - personal record (V)
猜你喜欢
如何在BNB链上创建BEP-20通证
Leetcode XOR operation
Leetcode dynamic planning training camp (1-5 days)
[text classification cases] (4) RNN and LSTM film evaluation Tendency Classification, with tensorflow complete code attached
Understanding various team patterns in scrum patterns
PHP reference manual string (7.2000 words)
C6748 software simulation and hardware test - with detailed FFT hardware measurement time
【文本分类案例】(4) RNN、LSTM 电影评价倾向分类,附TensorFlow完整代码
antd dropdown + modal + textarea导致的textarea光标不可被键盘控制问题
Shanda Wangan shooting range experimental platform project - personal record (V)
随机推荐
Efficient serial port cyclic buffer receiving processing idea and code 2
Shanda Wangan shooting range experimental platform project - personal record (IV)
Unity创建超写实三维场景的一般步骤
Openharmony open source developer growth plan, looking for new open source forces that change the world!
SRS 的部署
Physical meaning of FFT: 1024 point FFT is 1024 real numbers. The actual input to FFT is 1024 complex numbers (imaginary part is 0), and the output is also 1024 complex numbers. The effective data is
如何在BNB鏈上創建BEP-20通證
PCA based geometric feature calculation of PCL point cloud processing (52)
How does onlyoffice solve no route to host
还在用 ListView?使用 AnimatedList 让列表元素动起来
SIGIR'22 "Microsoft" CTR estimation: using context information to promote feature representation learning
基于pytorch搭建GoogleNet神经网络用于花类识别
Shanda Wangan shooting range experimental platform project - personal record (V)
Speex Wiener filter and rewriting of hypergeometric distribution
redis 分布式锁
LeetCode动态规划训练营(1~5天)
山东大学软件学院项目实训-创新实训-网络安全靶场实验平台(七)
MFC obtains local IP (used more in network communication)
Project training of Software College of Shandong University - Innovation Training - network security shooting range experimental platform (6)
Comment créer un pass BEP - 20 sur la chaîne BNB