当前位置:网站首页>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
边栏推荐
- Azkaban recompile, solve: could not connect to SMTP host: SMTP 163.com, port: 465 [January 10, 2022]
- MySQL数据库 - 单表查询(二)
- Electron入门教程3 ——进程通信
- Wave field Dao new species end up, how does usdd break the situation and stabilize the currency market?
- Shanda Wangan shooting range experimental platform project - personal record (V)
- Introduction to electron Tutorial 4 - switching application topics
- Mysql database - single table query (III)
- PCL点云处理之计算两平面交线(五十一)
- Database query - course selection system
- Why is the hexadecimal printf output of C language sometimes with 0xff and sometimes not
猜你喜欢
selenium. common. exceptions. WebDriverException: Message: ‘chromedriver‘ executable needs to be in PAT
aqs的学习
Fundamentals of programming language (2)
An error is reported when sqoop imports data from Mysql to HDFS: sqlexception in nextkeyvalue
selenium.common.exceptions.WebDriverException: Message: ‘chromedriver‘ executable needs to be in PAT
山东大学软件学院项目实训-创新实训-网络安全靶场实验平台(七)
Unity创建超写实三维场景的一般步骤
[numerical prediction case] (3) LSTM time series electricity quantity prediction, with tensorflow complete code attached
山东大学软件学院项目实训-创新实训-网络安全靶场实验平台(六)
Shanda Wangan shooting range experimental platform project - personal record (V)
随机推荐
Mysql database - single table query (I)
Unity general steps for creating a hyper realistic 3D scene
Efficient serial port cyclic buffer receiving processing idea and code 2
Five minutes to show you what JWT is
Unity 模型整体更改材质
PCL点云处理之基于PCA的几何形状特征计算(五十二)
Cadence Orcad Capture 批量更改元件封装功能介绍图文教程及视频演示
Cadence OrCAD capture batch change component packaging function introduction graphic tutorial and video demonstration
Cadence Orcad Capture CIS更换元器件之Link Database 功能介绍图文教程及视频演示
Notes of Tang Shu's grammar class in postgraduate entrance examination English
Lpc1768 optimization comparison of delay time and different levels
Mysql database - basic operation of database and table (II)
Video understanding
网络通信基础(局域网、广域网、IP地址、端口号、协议、封装、分用)
MFC obtains local IP (used more in network communication)
SIGIR'22「微软」CTR估计:利用上下文信息促进特征表征学习
山东大学软件学院项目实训-创新实训-网络安全靶场实验平台(五)
The textarea cursor cannot be controlled by the keyboard due to antd dropdown + modal + textarea
DTMF双音多频信号仿真演示系统
NC basic usage 1