データベースインスタンスに接続するためのJavaコード

パブリックメソッドDBUtilを記述して、ドライバーをロードします

package com.zq.framework.config.properties;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

import org.springframework.context.annotation.Configuration;

@Configuration
public class DBUtil {
	private static String URL = "jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8";
	private static String NAME = "root";
	private static String PASSWORD = "root";

	/**
	 * 连接驱动
	 * 
	 * @return
	 * @throws ClassNotFoundException
	 * @throws SQLException
	 */
	public static Connection getCon() throws ClassNotFoundException, SQLException {
		// 1.加载驱动程序
		Class.forName("com.mysql.cj.jdbc.Driver");
		// 2.获得数据库的连接
		Connection conn = DriverManager.getConnection(URL, NAME, PASSWORD);
		return conn;
	}

	/**
	 * 关闭连接
	 * 
	 * @param con
	 * @param state
	 * @throws SQLException
	 */
	public static void close(Connection con, Statement state) throws SQLException {
		if (con != null) {
			state.close();
			con.close();
		}
	}

}

 

データの挿入:

public static void inserExpress(String json) throws ClassNotFoundException, SQLException {
		Connection con = DBUtil.getCon();// 获取连接
		Statement state = con.createStatement(); // 获取Statement

		JSONObject object = JSONObject.parseObject(json);
		Map<String, Object> map = object.getJSONObject("result");
		for (Entry<String, Object> entry : map.entrySet()) {
			System.out.println(entry.getKey() + "=" + entry.getValue());
			String sql = "insert into express_code (name,express_code) values('" + entry.getValue() + "','"
					+ entry.getKey() + "')";
			int result;
			try {
				result = state.executeUpdate(sql);
				System.out.println(result + "行受影响");
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}

		DBUtil.close(con, state);// 关闭连接
	}

 

クエリデータ:

public static void selectExpressCode() throws ClassNotFoundException, SQLException {
		Connection con = DBUtil.getCon();// 获取连接
		Statement state = con.createStatement(); // 获取Statement
		String sql = "select * from express_code";
		ResultSet resultset = null;
		try {
			resultset = state.executeQuery(sql);
			while (resultset.next()) {
				String name = "" + resultset.getString("name");
				System.out.println(name);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		DBUtil.close(con, state);// 关闭连接
	}

}

 

おすすめ

転載: blog.csdn.net/qq_37557563/article/details/111505171
おすすめ