当前位置:网站首页>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