通过Java中的ssh连接(Jsch)从数据库中获取数据

时间:2018-08-19 20:43:32

标签: java mysql ssh jsch

因此我在树莓派上有一个名为barberDB的数据库。我可以使用MySQL Workbench从笔记本电脑通过ssh访问它,并且一切正常。但是现在我想通过Java代码在barberDB中写入数据。我已经写了一些类,但是出现以下错误java.sql.SQLException: Access denied for user 'root'@'localhost'

我有一个IOManager,在其中执行MySQL的工作。 ssh是在SSHManager中完成的,我的主应用程序创建了它们的实例,并试图从数据库中获取数据。使用便携式计算机上本地语言的测试数据库时,sql查询为我提供了信息,因此我认为使用ssh连接也可以。

public class IOManager {
public IOManager() {

}

Connection connection;

public boolean connectToMySql() {
    try {
        //Class.forName("com.mysql.jdbc.Driver").newInstance();
        connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/barberDB?useSSL=false&useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC", "root", "Demo_pw9");
        return true;
    }catch (Exception e) {
        e.printStackTrace();
        return false;
    }   
}

public void closeConnection() throws SQLException {
    connection.close();
}

public Vector loadCustomers(){
    Statement stmt = null;
    ResultSet result = null;

    try {
        stmt = connection.createStatement();
        result = stmt.executeQuery("SELECT * FROM CUSTOMER");
        result.first(); // <- first entry of the result set

        // STEP 2: copy the data from the result set into the vector
        Vector customers = new Vector();

        while(!result.isAfterLast()) // as long as valid data is in the result set
        {
            int id = result.getInt("ID");
            String name = result.getString("name");
            int isHaircut = result.getInt("isHaircut");
            int isBeard = result.getInt("isBeard");
            int isEyebrows = result.getInt("isEyebrows");
            int barberId = result.getInt("BARBER_ID");

            Kunde kunde = new Kunde(id, name, isHaircut, isBeard, isEyebrows, barberId);
            customers.add(kunde);
            result.next(); // go to next line in the customer table
        }

        // STEP 3: return the vector containing the customer data
        return customers;
    } catch (Exception ex) {
        System.out.println("Error during access + customern" + ex.getMessage());
        return null;
    }
}

public Vector loadBarbers(){
    Statement stmt = null;
    ResultSet result = null;

    try {
        stmt = connection.createStatement();
        result = stmt.executeQuery("SELECT * FROM barber");
        result.first(); // <- first entry of the result set

        // STEP 2: copy the data from the result set into the vector
        Vector barbers = new Vector();

        while(!result.isAfterLast()) // as long as valid data is in the result set
        {
            int id = result.getInt("barberID");
            String name = result.getString("barberName");

            Barber barber = new Barber(id, name);
            barbers.add(barber);
            result.next(); // go to next line in the customer table
        }

        // STEP 3: return the vector containing the customer data
        return barbers;
    } catch (Exception ex) {
        System.out.println("Error during access + barbern" + ex.getMessage());
        return null;
    }
}

这是我的IOManager。

public class SSHManager {
private String user;
private String password;
private String host;
private int port;
private String dbPath;

private ChannelSftp sftpChannel;

public SSHManager(String user, String password, String host, int port, String dbPath) {
    this.user = user;
    this.password = password;
    this.host = host;
    this.port = port;
    this.dbPath = dbPath;

}

public void sshConnect() {
    try {
        JSch jsch = new JSch();
        Session session = jsch.getSession(user, host, port);
        session.setPassword(password);
        session.setConfig("StrictHostKeyChecking", "no");
        System.out.println("Establishing Connection...");
        session.connect();
        System.out.println("Connection established.");
        System.out.println("Crating SFTP Channel.");
        sftpChannel = (ChannelSftp) session.openChannel("sftp");
        sftpChannel.connect();
        System.out.println("SFTP Channel created.");

        /*InputStream inputStream = sftpChannel.get(dbPath);

        try (Scanner scanner = new Scanner(new InputStreamReader(inputStream))) {
            while (scanner.hasNextLine()) {
                String line = scanner.nextLine();
                System.out.println(line);
            }
        }*/
    } catch (JSchException e) {
        e.printStackTrace();
    }
}

public ChannelSftp getSftp() {
    return this.sftpChannel;
}

}

这是SSHManager。扫描程序部分只是互联网上用于测试目的的一些代码段。

public class TestApp extends AConstants{

static int customerCount = 1;

public static void main(String args[]){
    int clmBarber = 1;

    JFrame frame = new JFrame("BURSEM APPLICATION");
    frame.setExtendedState(JFrame.MAXIMIZED_BOTH); 
    frame.setUndecorated(true);
    frame.setVisible(true);
    //frame.setUndecorated(true);

    double sizeX[] = {BORDER_WIDTH, BARBERNAME_WIDTH, BARBERNAME_WIDTH, BARBERNAME_WIDTH, BARBERNAME_WIDTH, BORDER_WIDTH}; // Columns
    double sizeY[] = {BORDER_HEIGHT, BARBERNAME_HEIGHT, BARBER_TOTAL_HEIGHT, CUSTOMER_HEIGHT, CUSTOMER_HEIGHT, CUSTOMER_HEIGHT, CUSTOMER_HEIGHT, CUSTOMER_HEIGHT, CUSTOMER_HEIGHT,  CUSTOMER_HEIGHT, BORDER_HEIGHT}; // Rows

    frame.setLayout(new TableLayout(new double[][] {sizeX,sizeY}));
    frame.getContentPane().setBackground(Color.BLACK);

    SSHManager sshManager = new SSHManager("ubuntu", "root12345", "192.168.178.99", 22, "");
    sshManager.sshConnect();

    IOManager iom = new IOManager();
    if(iom.connectToMySql() == false)
        return;

    setBarberLabel(frame, iom);
    setCustomerPanel(frame, iom);

    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setVisible(true);
}

public static JLabel getBarberNameLabel(String barberName) {
    JLabel barberNameLabel = new JLabel(barberName, SwingConstants.CENTER);
    barberNameLabel.setOpaque(false);
    barberNameLabel.setForeground(Color.WHITE);

    Map<TextAttribute, Object> attributes = new HashMap<TextAttribute, Object>();
    attributes.put(TextAttribute.UNDERLINE, TextAttribute.UNDERLINE_ON);
    barberNameLabel.setFont(barberNameLabel.getFont().deriveFont(LARGE_FONT));

    return barberNameLabel;
}

public static JPanel getBarberTotalPanel(int totalQueue, int totalTime) {
    double[] barberTotalX = new double[] {TableLayout.PREFERRED};
    double[] barberTotalY = new double[] {TableLayout.PREFERRED, 30, TableLayout.PREFERRED};

    JPanel barberTotalPanel = new JPanel();
    barberTotalPanel.setLayout(new TableLayout(new double[][] {barberTotalX, barberTotalY}));
    barberTotalPanel.setOpaque(true);
    barberTotalPanel.setBackground(ROW_COL_ONE);

    JLabel barberQueueTotalLabel = new JLabel("KUNDEN: " + String.valueOf(totalQueue), SwingConstants.LEFT);
    barberQueueTotalLabel.setOpaque(false);
    barberQueueTotalLabel.setFont(barberQueueTotalLabel.getFont().deriveFont(MEDIUM_FONT));
    barberTotalPanel.add(barberQueueTotalLabel, "0,0");

    JLabel barberTimeTotalLabel = new JLabel("GESAMTZEIT: " + String.valueOf(totalTime) + " Min", SwingConstants.LEFT);
    barberTimeTotalLabel.setOpaque(false);
    barberTimeTotalLabel.setFont(barberQueueTotalLabel.getFont().deriveFont(MEDIUM_FONT));
    barberTotalPanel.add(barberTimeTotalLabel, "0,2");

    return barberTotalPanel;
}

public static JPanel getCustomerPanel(String customerName,boolean isHaircut, boolean isBeard, boolean isEyebrows) {
    double[] customerX = new double[] {TableLayout.PREFERRED, TableLayout.PREFERRED, TableLayout.PREFERRED};
    double[] customerY = new double[] {TableLayout.PREFERRED, TableLayout.PREFERRED, TableLayout.PREFERRED};
    int customerTime = 0;

    JPanel customerPanel = new JPanel();
    customerPanel.setLayout(new TableLayout(new double[][] {customerX, customerY}));
    customerPanel.setOpaque(true);
    if(customerCount % 2 != 0) {
        customerPanel.setBackground(ROW_COL_TWO);
    }else {
        customerPanel.setBackground(ROW_COL_ONE);
    }

    JLabel customerNameLabel = new JLabel(customerName, SwingConstants.LEFT);
    customerNameLabel.setOpaque(false);
    customerNameLabel.setFont(customerNameLabel.getFont().deriveFont(MEDIUM_FONT));
    customerPanel.add(customerNameLabel, "0,0");

    JCheckBox customerHaircutCheckbox = new JCheckBox("Haarschnitt");
    customerHaircutCheckbox.setOpaque(false);
    customerHaircutCheckbox.setSelected(isHaircut);
    customerPanel.add(customerHaircutCheckbox, "0,1");

    JCheckBox customerBeardCheckbox = new JCheckBox("Bart");
    customerBeardCheckbox.setOpaque(false);
    customerBeardCheckbox.setSelected(isBeard);
    customerPanel.add(customerBeardCheckbox, "1,1");

    JCheckBox customerEyebrowsCheckbox = new JCheckBox("Augenbrauen");
    customerEyebrowsCheckbox.setOpaque(false);
    customerEyebrowsCheckbox.setSelected(isEyebrows);
    customerPanel.add(customerEyebrowsCheckbox, "2,1");

    if(isHaircut) {
        customerTime += 30;
    }
    if(isBeard) {
        customerTime += 15;
    }
    if(isEyebrows) {
        customerTime += 15;
    }

    JLabel customerTimeLabel = new JLabel("Dauer: " + customerTime + " Min", SwingConstants.LEFT);
    customerTimeLabel.setOpaque(false);
    customerTimeLabel.setFont(customerNameLabel.getFont().deriveFont(MEDIUM_FONT));
    customerPanel.add(customerTimeLabel, "0,2");

    customerCount++;


    return customerPanel;
}

public static void setCustomerPanel(JFrame frame, IOManager iom) {
    int rowCustomer = 3;
    Vector kunden = iom.loadCustomers();
    Enumeration e = kunden.elements();

    while(e.hasMoreElements()){
        Kunde customer = (Kunde) e.nextElement();
        System.out.println(customer);
        frame.add(getCustomerPanel(customer.getName(), customer.getIsHaircut(), customer.getIsBeard(), customer.getIsEyebrows()), "1,"+rowCustomer);
        System.out.println(rowCustomer);
        rowCustomer++;
    }
}

public static void setBarberLabel(JFrame frame, IOManager iom) {
    int clmBarber = 1;
    Vector barbers = iom.loadBarbers();
    Enumeration e = barbers.elements();

    while(e.hasMoreElements()){
        Barber barber = (Barber) e.nextElement();
        System.out.println(barber);
        frame.add(getBarberNameLabel(barber.getName()), clmBarber+",1");
        System.out.println(clmBarber);
        clmBarber++;
    }
}

这是我的主要应用程序。很抱歉,如果这个问题有点太长,希望它可以解决。

0 个答案:

没有答案