I created a program with a few lines of code after getting some advice her on Stackoverflow. My problem is that I can't connect to the database. I get an error called: [SQLITE_ERROR] SQL error or missing database (no such table: PasswordTable).
I created the database via SQLite and also get a successfull connection but cannot insert data. The database in SQLiteManager is called MyDB.sqlite and the table is called PasswordTable ...I am thankful for any help I can get :)
Also: Did I do the implementation of the inner class right? Is this appropriate?
Code is as follows:
import javax.swing.*;
public class Main {
public static void main (String [] args) {
JFrame frame = new JFrame ();
frame.setSize(500, 500);
frame.setResizable(false);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocation(700, 300);
frame.add(new FrameFunctionality ());
frame.setVisible(true);
}
}
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
public class FrameFunctionality extends JPanel {
JLabel label1;
JTextField tf1;
JButton but1;
Database db1;
public FrameFunctionality() {
setLayout(null);
//----Add a label to the frame
label1 = new JLabel("Passwort eingeben:");
label1.setBounds(10, 20, 150, 40);
add (label1);
//-------Add a tf to the frame
tf1 = new JTextField ();
tf1.setBounds(10, 50, 150, 40);
add (tf1);
//---Add a button to the frame
but1 = new JButton ("Save");
but1.setBounds(10, 100, 100, 50);
but1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
db1 = new Database ();
db1.insertData();
}
});
add (but1);
}
public class Database { //Inner Class
Connection con = null;
DriverManager man1 = null;
PreparedStatement pst = null;
public Database () {
//------Connect to the database
try {
Class.forName("org.sqlite.JDBC");
con = DriverManager.getConnection("jdbc:sqlite:MyDB.sqlite");
System.out.println("Connection: Ok!");
} catch (Exception e) {
System.out.println("Error1: " + e.getMessage());
}
}
//Insert data into the database
public void insertData () {
try {
String query = "INSERT INTO PasswordTable (Passwort) VALUES
(?)";
pst = con.prepareStatement(query);
pst.setString(1, tf1.getText());
pst.execute();
}catch (Exception e) {
System.out.println("Error2: " + e.getMessage());
}
}
}
}