I was trying to use Java to create a program that would allow me to insert, update, and delete entries on a MariaDB database running on a Pi 4 through the use of SSH from a remote session. This isn't something I have done before, as my database experience has been with XAMPP locally, but I wanted to see if I couldn't allow remote access, since it would be useful for this project. Currently, my code is set up to allow a user to operate a GUI to input data (the other functionality will come later), and is as follows:
public void actionPerformed(ActionEvent event) {
if(event.getSource() == submitButton){
String name = userField.getText();
String email = emailField.getText();
String system = systemField.getText();
String serial = serialField.getText();
String date = dateField.getText();
//SSH and DB insanity begins here
int localPort = 6000;
String sshUser ="";
String sshHost = "";
String dbHost = "192.168.1.242";
int dbPort = 3306;
String dbUser = "root";
String dbPassword = "wacky12";
String driver = "com.mysql.jdbc.Driver";
try{
JSch jsch = new JSch();
jsch.addIdentity("~/.ssh/id_rsa");
Session session = jsch.getSession(sshUser, sshHost, 22);
session.connect();
int forwardedPort = session.setPortForwardingL(0, dbHost, dbPort);
String url = "jdbc:mysql://localhost:" + forwardedPort;
Connection connection = DriverManager.getConnection(url, dbUser, dbPassword);
Statement stmt = connection.createStatement();
String insert = "insert into LaptopReturns('" + name + "' , '" + email + "' , '" + system + "' , '" + serial + "' , '" + date + "')";
stmt.execute(insert);
System.out.print("Done!");
}catch (Exception e) {
e.printStackTrace();
}
I fully realize that I am probably doing this wrong, but it doesn't seem to be connecting to the Pi at all when the submit button is hit. Is anyone able to give me some pointers? As mentioned I have no real experience with JSch. Also, would it be easier to have it connect to the server via SSH initially at run, or as needed when the button is pressed?