在Stackoverflow上获得一些建议后,我创建了一个包含几行代码的程序。我的问题是我无法连接到数据库。我收到一个错误:[SQLITE_ERROR] SQL错误或缺少数据库(没有这样的表:PasswordTable)。
我通过SQLite创建了数据库,并且还获得了成功的连接但无法插入数据。 SQLiteManager中的数据库名为MyDB.sqlite,该表名为PasswordTable ......我很感激能得到的任何帮助:)
另外:我是否正确执行内部类?这个合适吗?
代码如下:
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());
}
}
}
}