经过无数次的演练及实践和在网上查找资料,终于找到了解决方法,网上的方法好多都不行,通过询问大神才有了已下的思路:
1、首先连接跳板机(SSH)
2、通过跳板机去连接MySQL
3、通过SQL语句进行对数据库的操作
- JAVA使用JDBC连接MySQL数据库
首先要下载Connector/J地址:http://www.mysql.com/downloads/connector/j/
这是MySQL官方提供的连接方式:
还有一个是JSCH的jar包:
JSCH下载地址:http://download.csdn.net/detail/u013334392/9711999
解压后得到jar库文件,需要在工程中导入这两个库文件
我是用的是Eclipse:
- demo运行截图展示
- 通过以下代码示例来进行连接:
//connect主要是用于连接跳板机
public static void connect() {
String user = "root";//SSH用户名
String password = "pwd";//SSH密码
String host = "10.10.10.1";//SSH主机入口
int port = 22;//端口
try {
JSch jsch = new JSch();
session = jsch.getSession(user, host, port);
session.setPassword(password);
final Properties config = new Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
session.connect();
session.sendKeepAliveMsg();
} catch (Exception e) {
e.printStackTrace();
}
}
//作用于关闭连接
public static void disconnect() {
if (session != null)
session.disconnect();
}
以下是对数据库进行SQL命令执行及让SSH去连接MySQL数据库,将查询到的数据存放一个txt的文本文件中,并存放到服务器上的export目录下,根据当前查询时间进行命名(xxx_日期)以日期结尾来命名主要是作用于下一次的查询,可根据你最后一次查询到的时间来进行比较,获得最新的数据,届时只要把文件下载下来即可
public static void sendCommand(String sql) {
ChannelExec channel = null;
try {
channel = (ChannelExec) session.openChannel("exec");
// 日志文件名
String logFileName = textName + new SimpleDateFormat("yyyyMMddHHmmss").format(new Date().getTime())
+ ".txt";
System.out.println("新的文件名:" + logFileName);
sb.append("文件名:" + logFileName + "\r\n");
/**
-u MySQL数据库用户名(注意没空格) 如:-uroot
-p MySQL数据库密码(注意没空格) 如:-pmypwd
-h MySQL数据库主机(注意没空格) 如:-h10.10.10.2
--default-character-set=utf8 表示编码格式(如果不加会出现中文乱码)
-e 请求空格后面接SQL语句(注意用双引号包起来)
SQL语句 空格后面接数据库名 如:bankinfo
数据库后面接 > export(文件存放目录)/文件名
*/
channel.setCommand("mysql -uroot -pmypwd -h10.10.10.2 --default-character-set=utf8 -e \"" + sql
+ "\" bankinfo > export/" + logFileName);
//进行连接
channel.connect();
// 将文件下载下来
Thread.currentThread().sleep(10000);
String descFileName = sourceFile.getAbsolutePath() + File.separator + logFileName;
//将最新查询到的数据下载到本地文件目录上
download(logFileName, descFileName);
System.out.println("disconnect..exist.");
sb.append("disconnect..exist.\r\n");
//读取是否有新的数据更新
if (readTxtFile(descFileName)) {
sb.append("<<<<<<.......有新的数据.......>>>>>>");
//进行筛选复制
FileOperateDemo.copyFile(descFileName, sourceFile + File.separator + "completeFile");
//弹出警告对话框进行提示
int option = JOptionPane.showConfirmDialog(null, "有提现数据更新,请查看!", "有数据更新", JOptionPane.YES_OPTION,
JOptionPane.WARNING_MESSAGE, null);
if (option == JOptionPane.YES_OPTION) {
System.out.println("descFileName=" + descFileName + "--COMPLETEFILE=" + sourceFile + File.separator
+ "completeFile");
JOptionPane.showConfirmDialog(null, descFileName, "文件路径", JOptionPane.YES_OPTION,
JOptionPane.INFORMATION_MESSAGE, null);
}
} else {
sb.append("<<<<<<.......没有新的数据.......>>>>>>");
}
textArea.setText(sb.toString());
} catch (JSchException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (channel != null)
channel.disconnect();
}
}
- 将服务器上存储的文件下载下来存入目标文件下
public static void download(String logFileName, String descFileName) {
ChannelSftp chSftp = null;
try {
chSftp = (ChannelSftp) session.openChannel("sftp");
chSftp.connect();
if (!sourceFile.exists())
sourceFile.mkdirs();
chSftp.get("export/" + logFileName, descFileName);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (chSftp != null)
chSftp.disconnect();
}
}
- swingUI界面编写实现
// new出一个文本域用于展示数据
static TextArea textArea = new TextArea();
// new出一个文本域用于展示数据
static TextArea taComplete = new TextArea();
static JButton startButton = new JButton("点击开始");
static TextField sourText = new TextField();
// 南 south 东east 西Western 北north
public static void generateFormView() {
JFrame f = new JFrame("提现查询");
f.setLayout(new BorderLayout());
// 设置禁止编辑
textArea.setEditable(false);
textArea.setBackground(Color.WHITE);
f.add(textArea, BorderLayout.CENTER);
JPanel southPanel = new JPanel();
southPanel.setLayout(new BorderLayout());
JButton btnComplete = new JButton("点击有提现数据文件名");
btnComplete.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String sourTexts = sourText.getText().trim();
if (sourTexts == null || sourTexts.equals("") || "请填写源路径".equals(sourTexts)) {
JOptionPane.showConfirmDialog(null, "源路径不能为空,请在文本框内输入路径!", "输入目录路径", JOptionPane.YES_OPTION,
JOptionPane.WARNING_MESSAGE, null);
sourText.setText("");
} else {
sourceFile = new File(sourTexts);
File completeFile = new File(sourceFile + File.separator + "completeFile");
if (!completeFile.exists())
completeFile.mkdirs();
completeSB.setLength(0);
readCompleteFile(new File(sourceFile + File.separator + "completeFile"));
if (completeSB.length() <= 0) {
taComplete.setText("还未有查询到更新的数据。。。。。");
} else {
taComplete.setText(completeSB.toString());
}
}
}
});
southPanel.add(btnComplete, BorderLayout.EAST);
startButton.setPreferredSize(new Dimension(100, 20));
startButton.addActionListener(startListener);
southPanel.add(startButton, BorderLayout.WEST);
southPanel.setPreferredSize(new Dimension(400, 40));
f.add(southPanel, BorderLayout.SOUTH);
f.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
int exi = JOptionPane.showConfirmDialog(null, "要退出该程序吗?", "友情提示", JOptionPane.YES_NO_OPTION,
JOptionPane.QUESTION_MESSAGE);
if (exi == JOptionPane.YES_OPTION) {
System.exit(0);
} else {
return;
}
}
});
JPanel jpComplete = new JPanel();
jpComplete.setLayout(new BorderLayout());
// 设置禁止编辑
taComplete.setEditable(false);
taComplete.setBackground(Color.WHITE);
jpComplete.add(taComplete, BorderLayout.CENTER);
jpComplete.setPreferredSize(new Dimension(400, 600));
f.add(jpComplete, BorderLayout.EAST);
JPanel labPanel = new JPanel();
JLabel labTime = new JLabel();
new Timer().schedule(new TimerTask() {
@Override
public void run() {
getSystemTime(labTime);
}
}, 0, 1000);
labPanel.add(labTime, BorderLayout.WEST);
sourText.setColumns(24);
labPanel.add(sourText, BorderLayout.CENTER);
JButton btnClear = new JButton("清除全部");
btnClear.setPreferredSize(new Dimension(100, 30));
btnClear.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
completeSB.setLength(0);
sb.setLength(0);
textArea.setText("");
taComplete.setText("");
}
});
labPanel.add(btnClear, BorderLayout.SOUTH);
southPanel.add(labPanel, BorderLayout.CENTER);
f.setSize(800, 600);
f.setLocationRelativeTo(null);
f.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
f.setVisible(true);
}
- 用于读取文件
static StringBuilder completeSB = new StringBuilder();
public static void readCompleteFile(File file) {
if (!file.exists())
return;
if (file.isDirectory()) {
for (File f : file.listFiles()) {
if (f.isDirectory())
readCompleteFile(f);
else if (f.isFile())
completeSB.append(f.getName() + "\r\n");
}
}
}
- 开始查询按钮事件监听
static ActionListener startListener = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String sourTexts = sourText.getText().trim();
if (sourTexts == null || sourTexts.equals("") || "请填写源路径".equals(sourTexts)) {
JOptionPane.showConfirmDialog(null, "源路径不能为空,请在文本框内输入路径!", "输入目录路径", JOptionPane.YES_OPTION,
JOptionPane.WARNING_MESSAGE, null);
sourText.setText("");
} else {
sourceFile = new File(sourTexts);
if (!sourceFile.exists())
sourceFile.mkdirs();
startButton.setEnabled(false);
textArea.setText("开始查询.....");
// 使用定时器,每半个小时执行一次
startTimerTask();
}
}
};
- 获得系统时间
public static void getSystemTime(JLabel label) {
Date date = new Date();
DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String time = format.format(date);
label.setText("当前的时间是:" + time);
}
- 格式化时间戳
public static String getFormatDateTime(long time) {
return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(time > 0 ? time : new Date().getTime()));
}
- 启动定时器,每半个钟进行查询一次,注意getQuerySql(是最后一次查询过的时间)
public static void startTimerTask() {
Timer timer = new Timer();
timer.schedule(new TimerTask() {
public void run() {
try {
// 启动连接
connect();
long max = 0;
if (sourceFile.exists()) {
if (sourceFile.isDirectory()) {
File[] fs = sourceFile.listFiles();
for (int i = 0; i < fs.length; i++) {
if (fs[i].isDirectory())
continue;
String strI = fs[i].getName().substring(textName.length(),
fs[i].getName().lastIndexOf("."));
long fileNameI = new SimpleDateFormat("yyyyMMddHHmmss").parse(strI).getTime();
for (int j = 0; j < fs.length; j++) {
if (fs[j].isDirectory())
continue;
String strJ = fs[j].getName().substring(textName.length(),
fs[j].getName().lastIndexOf("."));
long fileNameJ = new SimpleDateFormat("yyyyMMddHHmmss").parse(strJ).getTime();
if (fileNameI > fileNameJ)
max = fileNameI;
else
max = fileNameJ;
}
}
}
}
String dateTime = getFormatDateTime(max);
sb.append("\r\n--------------------------------------------------------------\r\n");
sb.append("最后一次查询过的时间:timestamp:" + max + "--dateTime:" + dateTime + "\r\n");
sendCommand(getQuerySql(dateTime));
} catch (Exception ex) {
ex.printStackTrace();
} finally {
disconnect();
}
}
}, 0, 1800000);// 设定指定的时间time,此处为2000毫秒 30分钟1800000毫秒
}
/**
* 功能:Java读取txt文件的内容 步骤:1:先获得文件句柄 2:获得文件句柄当做是输入一个字节码流,需要对这个输入流进行读取
* 3:读取到输入流后,需要读取生成字节流 4:一行一行的输出。readline()。 备注:需要考虑的是异常情况
*
* @param filePath
*/
public static boolean readTxtFile(String filePath) {
boolean notEmpty = false;
try {
String encoding = "GBK";
File file = new File(filePath);
if (file.isFile() && file.exists()) { // 判断文件是否存在
InputStreamReader read = new InputStreamReader(new FileInputStream(file), encoding);// 考虑到编码格式
BufferedReader bufferedReader = new BufferedReader(read);
String lineTxt = null;
while ((lineTxt = bufferedReader.readLine()) != null) {
notEmpty = true;
}
read.close();
} else {
notEmpty = false;
System.out.println("找不到指定的文件");
}
} catch (Exception e) {
notEmpty = false;
System.out.println("读取文件内容出错");
e.printStackTrace();
}
return notEmpty;
}
public static void main(String[] args) {
sourText.setText("请填写源路径");
generateFormView();
}