java读取数据库,操作相关数值

一、先准备好mysql的基本环境。

    详细见https://blog.csdn.net/weixin_42575806/article/details/80941917

二、下载mysql-connector-java-8.0.11.jar的jira包放到项目lib目录下

        下载地址https://dev.mysql.com/downloads/connector/j/

java读取数据库,操作相关数值_第1张图片


java读取数据库,操作相关数值_第2张图片

三、创建数据库表结构

DROP TABLE IF EXISTS `base_app_version`;
CREATE TABLE `base_app_version` (
  `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主键',
  `version_id` varchar(50) DEFAULT '' COMMENT '版本号',
  `type` int(2) DEFAULT '0' COMMENT '0:安卓,1:ISO',
  `version_url` varchar(200) DEFAULT '' COMMENT '版本URL',
  `city_code` varchar(6) DEFAULT '',
  `create_time` varchar(14) DEFAULT '' COMMENT '创建时间',
  `force_to_update` bit(1) DEFAULT b'0' COMMENT '是否强制更新',
  `content_desc` varchar(800) NOT NULL COMMENT '更新内容描述',
  `soft_type` int(2) DEFAULT '0' COMMENT '0:用户端,1:司机端',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8 ROW_FORMAT=DYNAMIC COMMENT='app版本表';

-- ----------------------------
-- Records of base_app_version
-- ----------------------------
INSERT INTO `base_app_version` VALUES ('3', 'V1.0.0', '0', '', '420100', '2018 07 05 11 30 00', '\0', 'sdfsdfsdfsfdsdfsdf', '0');

四、创建java工程

    4.1 主入口  (text.java )

package test0705;

public class text {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		System.out.println("I coming for test connet mysql!");
		JdbcTest1.connetMysql();

	}

}

    4.2 创建表对应的类文件(BaseAppVersion.java)

package test0705;

import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

//CREATE TABLE `base_app_version` (
//		  `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主键',
//		  `version_id` varchar(50) DEFAULT '' COMMENT '版本号',
//		  `type` int(2) DEFAULT '0' COMMENT '0:安卓,1:ISO',
//		  `version_url` varchar(200) DEFAULT '' COMMENT '版本URL',
//		  `city_code` varchar(6) DEFAULT '',
//		  `create_time` varchar(14) DEFAULT '' COMMENT '创建时间',
//		  `force_to_update` bit(1) DEFAULT b'0' COMMENT '是否强制更新',
//		  `content_desc` varchar(800) NOT NULL COMMENT '更新内容描述',
//		  `soft_type` int(2) DEFAULT '0' COMMENT '0:用户端,1:司机端',
//		  PRIMARY KEY (`id`)
//		) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8 ROW_FORMAT=DYNAMIC COMMENT='app版本表';

public class BaseAppVersion {

	private int id;
	private String version_id;
	private int type;
	private String version_url;
	private String city_code;
	private String create_time;
	private int force_to_update;
	private String content_desc;
	private int soft_type;
	
	BaseAppVersion(int id,String  version_id,int type,String version_url,String city_code,
				   String create_time,int force_to_update,String content_desc,int soft_type) {
         this.id = id; 
         this.version_id = version_id;
         this.type = type;
         this.version_url = version_url;
         this.city_code = city_code; 
         this.create_time = create_time;
         this.force_to_update = force_to_update;
         this.content_desc = content_desc;
         this.soft_type = soft_type;   
     }
	
	BaseAppVersion() {}
	
	 public int getId() {
         return id;
     }
     public void setId(int newid) {
         this.id = newid;
     }
     
     public String getVersionId() {
         return version_id;
     }
     public void setVersionId(String newversion_id) {
         this.version_id = newversion_id;
     }
     
     public int getType() {
         return type;
     }
     public void setType(int newtype) {
         this.type = newtype;
     }
     
     public String getversion_url() {
         return version_url;
     }
     public void setversion_url(String newversion_url) {
         this.version_url = newversion_url;
     }
     
     public String getcity_code() {
         return city_code;
     }
     public void setcity_code(String newcity_code) {
         this.city_code = newcity_code;
     }
 
     public String getcreate_time() {
         return create_time;
     }
     public void setcreate_time(String newcreate_time) {
         this.create_time = newcreate_time;
     }

     public int getforce_to_update() {
         return force_to_update;
     }
     public void setforce_to_update(int newforce_to_update) {
         this.force_to_update = newforce_to_update;
     }
 
     public String getcontent_desc() {
         return content_desc;
     }
     public void setcontent_desc(String newcontent_desc) {
         this.content_desc = newcontent_desc;
     }
     
     public int getsoft_type() {
         return soft_type;
     }
     public void setsoft_type(int newsoft_type) {
         this.soft_type = newsoft_type;
     }
     
     //读取数据库表结构值存在到当前类中
     public static List SelectBaseAppVersionData(Statement stmt, String sqlstr) throws SQLException{
 		List list = new ArrayList();
 		ResultSet rs = stmt.executeQuery(sqlstr);//查询多个表
 		ResultSetMetaData md = rs.getMetaData();
        int col = md.getColumnCount();
 		while(rs.next()){
 			BaseAppVersion bav = new BaseAppVersion();
 			
			bav.setId(rs.getInt("id"));
			bav.setVersionId(rs.getString("version_id"));
			bav.setType(rs.getInt("type"));
			bav.setversion_url(rs.getString("version_url"));
			bav.setcity_code(rs.getString("city_code"));
			bav.setcreate_time(rs.getString("create_time"));
			bav.setforce_to_update(rs.getInt("force_to_update"));
			bav.setcontent_desc(rs.getString("content_desc"));
			bav.setsoft_type(rs.getInt("soft_type")); 				  
			 			
			list.add(bav);
 		   }
 		
 		if( rs != null){
 			try{
 				rs.close();
 			} catch (SQLException e){
 				System.out.println("ResultSet 关闭时出现错误!");
 				e.printStackTrace();
 			}
 		}
 		return list;
 	}

     //显示当前类查询值
     public static void showBaseAppVersion(BaseAppVersion bav) {   
	   System.out.println(" List for BaseAppVersion " + " id: "+ bav.getId()+ " version_id: "+ bav.getVersionId()
			   			+ " type: "+ bav.getType() + " version_url: "+ bav.getversion_url() + " city_code: "+ bav.getcity_code()
			   			+ " create_time: "+ bav.getcreate_time()+ " force_to_update: "+ bav.getforce_to_update()
			   			+ " content_desc: "+ bav.getcontent_desc() + " soft_type: "+ bav.getsoft_type());
	}
     
}
4.3 创建数据操作文件(JdbcTest1.java)
package test0705;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.ResultSet;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class JdbcTest1 {

	//获取当前时间,按照固定格式例如:yyyyMMddHHmmss
	public static String getCurrentTime( String timeFormat){
		 LocalDateTime arrivalDate  = LocalDateTime.now().withNano(0);
		 DateTimeFormatter format = DateTimeFormatter.ofPattern(timeFormat);
         String nowTime = arrivalDate.toString().replaceAll("T", "");
         nowTime = arrivalDate.format(format);

         System.out.println("arrivalDate: " +  arrivalDate + " nowTime: " + nowTime);
         return nowTime;
	}
	
	//显示当前时间类型
	public static void showTime(){
		 LocalDate today = LocalDate.now();
	     LocalTime time = LocalTime.now();
	     System.out.println("today: " + today + " time: " + time.withNano(0));
	     
	     int year = today.getYear();
	     int month = today.getMonthValue();
	     int day = today.getDayOfMonth();
	     System.out.println("Year : "+ year + " Month :" + month + " day :" + day );
	     
	     LocalTime newTime = time.plusHours(2); // adding two hours
	     System.out.println("Time after 2 hours : " +  newTime);     
	}
	
	//1.数据库删除
	public static int DeleteData(Statement stmt, String sqlstr) throws SQLException{
		int re = stmt.executeUpdate(sqlstr);
		if(re != -1){
			System.out.println(sqlstr + "数据库值删除成功!"); 
		} else {
			System.out.println(sqlstr + "数据库值删除失败!"); 
		}
		
		return re;
	}
	
	//2.数据库增加
	public static int AddData(PreparedStatement ps) throws SQLException{
		int re = ps.executeUpdate();//执行sql语句            
		if(re != -1){
			System.out.println(ps.toString() + "数据库插入成功!"); 
		} else {
			System.out.println(ps.toString() + "数据库插入失败!"); 
		}
		
		return re;
	}
	
	//3.数据库更新
	public static int UpdateData(Statement stmt, String sqlstr) throws SQLException{
		int re = stmt.executeUpdate(sqlstr);
		if(re != -1){
			System.out.println(sqlstr + "数据库更新成功!"); 
		} else {
			System.out.println(sqlstr + "数据库更新失败!"); 
		}
		
		return re;
	}
	
	//4.数据库查找
	public static int SelectData(Statement stmt, String sqlstr) throws SQLException{
		ResultSet rs = stmt.executeQuery(sqlstr);//查询多个表
        int col = rs.getMetaData().getColumnCount();
		while(rs.next()){
			for (int i = 1; i <= col; i++) {
				System.out.print(rs.getString(i) + "\t");
			}
			System.out.println("\n==========================================================================================");
		}
		
		if( rs != null){
			try{
				rs.close();
			} catch (SQLException e){
				System.out.println("ResultSet 关闭时出现错误!");
				e.printStackTrace();
			}
		}
		return 1;
	}
	
	//不区分class类别进行数据库查找
	public static List newSelectData(Statement stmt, String sqlstr) throws SQLException{
		List list = new ArrayList();
		ResultSet rs = stmt.executeQuery(sqlstr);//查询多个表
		ResultSetMetaData md = rs.getMetaData();
		
        int col = md.getColumnCount();
		while(rs.next()){
			Map rowData = new HashMap();
			
			for (int i = 1; i <= col; i++) {
				rowData.put(md.getColumnName(i),rs.getObject(i));
			}
			list.add(rowData);
	    }
		
		if( rs != null){
			try{
				rs.close();
			} catch (SQLException e){
				System.out.println("ResultSet 关闭时出现错误!");
				e.printStackTrace();
			}
		}
		return list;
	}
		
	public static void connetMysql(){
		
		Connection conn = null;// conn用于连接数据库
        Statement stmt = null;// stmt用于发送sql语句到数据库并执行sql语句
        String sqlstr = null;
        String connectionString  = "jdbc:mysql://10.1.254.180:3306/wptest?user=wp&password=123456&useUnicode=true&";
		
		try{
//			Class.forName("com.mysql.jdbc.Driver").newInstance(); 老版本数据1.8版本前的连接方式
			Class.forName("com.mysql.cj.jdbc.Driver").newInstance();//新版本连接方式
			
			System.out.println(connectionString);
			conn = DriverManager.getConnection(connectionString);
			System.out.println("connect success!");
            stmt = conn.createStatement();
            
            showTime();//just for test time and date
            
          //1.数据库删除
            int st = 0;
			sqlstr = "DELETE FROM base_app_version WHERE soft_type = " + st +";";
			DeleteData(stmt,sqlstr);
			
			//2.数据库增加
			sqlstr = "INSERT INTO `base_app_version` VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?);";
			PreparedStatement ps = conn.prepareStatement(sqlstr);//创建一个Statement对象
            ps.setInt(1,0);//id
            ps.setString(2,"V1.0.1");//version_id
            ps.setInt(3,0);//type
            ps.setString(4,"");//version_url
            ps.setString(5,"420101");//city_code
            ps.setString(6, getCurrentTime("yyyyMMddHHmmss"));//create_time
            ps.setInt(7,0);//force_to_update
            ps.setString(8,"mytestinsert");//content_desc
            ps.setInt(9,0);//soft_type
            AddData(ps);
            
			//3.数据库更新
			sqlstr = "UPDATE base_app_version SET city_code = '420111' WHERE soft_type = " + st +";";
			UpdateData(stmt, sqlstr);

            //4.数据库查找
            sqlstr = "Select * from base_app_version;";
            SelectData(stmt,sqlstr);//查找数据库所有字段值
            BaseAppVersion bav = new BaseAppVersion();
            List baseAppVersionL  = bav.SelectBaseAppVersionData(stmt,sqlstr);

            for(int i=0; i



你可能感兴趣的:(java技术)