1. 程式人生 > >mysql操作類

mysql操作類

創作不易,請勿抄襲,轉載請註明出處。如有疑問,請加微信 wx15151889890,謝謝。
[本文連結:]https://blog.csdn.net/wx740851326/article/details/https://blog.csdn.net/wx740851326/article/details/83744662

本文主要寫了如何測試連線mysql資料庫,sql操作資料庫以及讀出來的資料逐行處理,如有錯誤,請不吝賜教。

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

import redis.clients.jedis.JedisCluster;
/**
 * define mysql handlers
 * 
 * @author dmvoishi
 * @since  20181024
 */
public class MysqlUtil {
	static JedisCluster jedisCluster = RedisUtil.getJedisCluster();

	public static void main(String[] args) {
		String mysqlConfigPath = "hdfs:///user/hdfs/mysql.cfg";
		// 宣告Connection物件
		Connection con;
		Properties prop = CommonUtils.getProperty(mysqlConfigPath, "hdfs");

		// 驅動程式名
		// String driver = "com.mysql.jdbc.Driver";
		String driver = prop.getProperty("driver");
		// URL指向要訪問的資料庫名mydata
		// String url = "jdbc:mysql://10.0.0.1:3306/";
		String url = prop.getProperty("url");

		// MySQL配置時的使用者名稱
		// String user = "root";
		String user = prop.getProperty("user");

		// MySQL配置時的密碼
		// String password = "root";
		String password = prop.getProperty("password");

		// 遍歷查詢結果集
		try {
			// 載入驅動程式
			Class.forName(driver);
			// 1.getConnection()方法,連線MySQL資料庫!!
			con = DriverManager.getConnection(url, user, password);
			if (!con.isClosed())
				System.out.println("Succeeded connecting to the Database!");
			// 2.建立statement類物件,用來執行SQL語句!!
			Statement statement = con.createStatement();
			// 要執行的SQL語句
			// String sql = "select plc_name,plc_data_name,id from alarm";
			String sql = "select CONCAT(plc_name,\"_alarm\") plc_name,CONCAT(\"{\",GROUP_CONCAT(CONCAT(\"\"\"\",plc_data_name,\"\"\"\",\":\",\"\"\"\",id,\"\"\"\")),\"}\") alarm_content from alarm GROUP BY plc_name";
			// 3.ResultSet類,用來存放獲取的結果集!!
			// statement.executeQuery(sql);
			ResultSet rs = statement.executeQuery(sql);

			String plc_name = "plc_name";
			String alarm_content = "alarm_content";
			while (rs.next()) {
				plc_name = rs.getString("plc_name");
				alarm_content = rs.getString("alarm_content");
				jedisCluster.set(plc_name, alarm_content);
				// System.out.println(plc_name);
				// System.out.println(alarm_content);
			}
			rs.close();
			con.close();
		} catch (ClassNotFoundException e) {
			// 資料庫驅動類異常處理
			System.out.println("Sorry,can`t find the Driver!");
			e.printStackTrace();
		} catch (SQLException e) {
			// 資料庫連線失敗異常處理
			e.printStackTrace();
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		} finally {
			System.out.println("資料庫資料成功獲取!!");
		}
	}
}