mysql查询两个不同的服务器数据库.

版权声明: https://blog.csdn.net/eds124/article/details/84789886
package com.dinglin;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Hashtable;
import java.util.Vector;

public class Main {
	private static final String className = "com.mysql.jdbc.Driver";
	private static final String url = "";
	private static final String user = "root";
	private static final String password = "";

	private static Connection c = null;
	private static PreparedStatement ps = null;
	private static ResultSet rs = null;

	static {
		try {
			Class.forName(className);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public Main(String url, String user, String password, String sql) {
		try {
			c = DriverManager.getConnection(url, user, password);
			ps = c.prepareStatement(sql);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static void main(String[] args) {
		Vector<Hashtable<String, Object>> vhso = select();
		for (Hashtable<String, Object> hso : vhso) {
			System.out.println(hso.get("username"));
			System.out.println(hso.get("password"));
		}
	}

	public static Vector<Hashtable<String, Object>> select() {
		Vector<Hashtable<String, Object>> vhso = new Vector<Hashtable<String, Object>>();
		try {
			c = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/mydata", user, password);
			ps = c.prepareStatement("select * from t_user");
			rs = ps.executeQuery();
			while (rs.next()) {
				Hashtable<String, Object> hso = new Hashtable<String, Object>();
				hso.put("username", rs.getString("username"));
				hso.put("password", rs.getString("password"));
				vhso.add(hso);
			}

			c = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/mydata", user, password);
			ps = c.prepareStatement("select * from t_user");
			rs = ps.executeQuery();
			while (rs.next()) {
				Hashtable<String, Object> hso = new Hashtable<String, Object>();
				hso.put("username", rs.getString("username"));
				hso.put("password", rs.getString("password"));
				vhso.add(hso);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return vhso;
	}
}

猜你喜欢

转载自blog.csdn.net/eds124/article/details/84789886
今日推荐