【问题标题】:Trying to take data from JFrame and insert into SQLite. Connection works but insertion only inserts blank line. Why?试图从 JFrame 中获取数据并插入 SQLite。连接有效,但插入仅插入空行。为什么?
【发布时间】:2018-01-23 10:25:24
【问题描述】:

我正在尝试使用“insertSQLB1”方法将一些数据插入到我的 SQLite 数据库中。但是,每次我在 TextField 中输入内容时,它只会在数据库中插入一个空行。我仍然是 Java 的初学者,感谢我能得到的所有建议 :)

代码如下:

import javax.swing.*;

public class Main {
 public static void main(String args[]) {

  JFrame frame1 = new JFrame();
  frame1.setTitle("Password Saver");
  frame1.setSize(600, 600);
  frame1.setLocation(800, 200);
  frame1.setResizable(false);
  frame1.add(new JFrameFunctionality());
  frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  frame1.setVisible(true);
 }
}

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.*;


public class JFrameFunctionality extends JPanel {


 JTextField tf1;
 JTextField tf2;
 JTextField tf3;
 PreparedStatement prepstat = null;


 public JFrameFunctionality() {

   setLayout(null);

   //FIRST PART - Create a JLabel to let the user know what to enter in 
   first TextField
   JLabel label1 = new JLabel("Neues Passwort:");
   label1.setBounds(50, 70, 150, 40);
   add(label1);

   //FIRST PART - Create first TextField to enter password
   tf1 = new JTextField();
   tf1.setBounds(50, 100, 150, 40);
   add(tf1);
   repaint();

   //FIRST PART - Create second TextField to enter name of the program
   tf2 = new JTextField();
   tf2.setBounds(50, 140, 150, 40);
   add(tf2);
   repaint();

   //FIRST PART - Create first button to add new password
   JButton button1 = new JButton("Add new Password");
   button1.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
     codeforButtons cfBobj1 = new codeforButtons();
     cfBobj1.insertSQLB1();
    }
   });

   button1.setBounds(200, 100, 150, 30);
   add(button1);

   //SECOND PART - Create a JLabel to let the user know where to enter when changing password 
   JLabel label2 = new JLabel("Enter new Password for change:");
   label2.setBounds(50, 170, 200, 40);
   add(label2);

   //SECOND PART//Create second TextField to enter a new Password when changing Password
   tf3 = new JTextField();
   tf3.setBounds(50, 200, 150, 40);
   add(tf3);

   //SECOND PART//Create second button to take the changed Password and put it where the old password was   
   JButton button3 = new JButton("Change Password");
   button3.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {}
   });
   button3.setBounds(200, 200, 150, 30);
   add(button3);

   //THIRD PART//Create third button to display a existing password
   JButton button2 = new JButton("Display Password");
   button2.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
     //DatabaseConnection con2 = new DatabaseConnection ();
     //con2.listPasswords();
    }
   });
   button2.setBounds(200, 250, 150, 30);
   add(button2);
  } //Konstruktur Ende

 public String retrieveTextTF1() { //Retrieve Text from TextField 1
  return tf2.getText();
 }

}

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.Statement;
import java.sql.ResultSet;

import javax.swing.JOptionPane;

public class codeforButtons extends JFrameFunctionality {

 Connection con1 = null;
 Connection con2 = null;
 PreparedStatement stat1 = null;
 Statement stat2 = null;
 ResultSet rs = null;


 public void getConnection() { //Establishes a connection to the database "passwords"
  try {
   Class.forName("org.sqlite.JDBC");
   con1 =
    DriverManager.getConnection("JDBC:sqlite:PasswordDatabase.sqlite");
   System.out.println("Connection established...");

  } catch (Exception e) {
   System.out.println("Error: " + " " + e.getMessage());
  }

 }

 public void insertSQLB1() { //Inserts the application name into the database *not working, inserts only a blank row*
  try {
   getConnection();
   String query = "INSERT INTO passwords (Anwendung) VALUES (?)";
   PreparedStatement stat1 = con1.prepareStatement(query);
   stat1.setString(1, tf2.getText());
   stat1.execute();
   JOptionPane.showMessageDialog(null, "Data saved!");

   con1.close();

  } catch (Exception e) {
   System.out.println("Error: " + e.getMessage());
  }

 }

 public void listPasswords() { //Gibt alle Passwörter aus der Datenbank aus und unterbricht dann die Verbindung zur DB
  try {
   getConnection();
   this.stat2 = con2.createStatement();
   ResultSet rs = stat1.executeQuery("SELECT * FROM passwords");

   while (rs.next()) {
    String password = rs.getString("Passwort");
    String program = rs.getString("Anwendung");

    System.out.println("Passwort: " + password + " " + "Anwendung: " + program);
   }
  } catch (Exception e) {
   System.out.println("Error: " + e.getMessage());
  }

 }

}

【问题讨论】:

  • @pfranza nope。在代码审查中,只有工作代码是on-topic
  • 您确认您的tf2.getText() 确实在返回文本吗?
  • 试过单步执行代码吗?

标签: java sqlite jdbc jframe insertion


【解决方案1】:

问题是您的codeforButtons 类扩展了JFrameFunctionality,因此它获得了自己的tf2 实例,该实例隐藏了显示中使用的实例。 (您正在创建 2 个 tf2 实例)

codeforButtons 移动为JFrameFunctionality 的嵌套内部类,然后从codeforButtons 中删除extends JFrameFunctionality,您将拥有读取tf2 变量的正确范围。

见下文:

public class JFrameFunctionality extends JPanel {

    JTextField tf1;
    JTextField tf2;
    JTextField tf3;
    PreparedStatement prepstat = null;

    public JFrameFunctionality() {

        setLayout(null);

        // FIRST PART - Create a JLabel to let the user know what to enter in
        // first TextField
        JLabel label1 = new JLabel("Neues Passwort:");
        label1.setBounds(50, 70, 150, 40);
        add(label1);

        // FIRST PART - Create first TextField to enter password
        tf1 = new JTextField();
        tf1.setBounds(50, 100, 150, 40);
        add(tf1);
        // repaint();

        // FIRST PART - Create second TextField to enter name of the program
        tf2 = new JTextField();
        tf2.setText("test");
        tf2.setBounds(50, 140, 150, 40);
        add(tf2);
        // repaint();

        // FIRST PART - Create first button to add new password
        JButton button1 = new JButton("Add new Password");
        button1.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                System.out.println("::" + tf2.getText());
                codeforButtons cfBobj1 = new codeforButtons();
                cfBobj1.insertSQLB1();
            }
        });

        button1.setBounds(200, 100, 150, 30);
        add(button1);

        // SECOND PART - Create a JLabel to let the user know where to enter when changing password
        JLabel label2 = new JLabel("Enter new Password for change:");
        label2.setBounds(50, 170, 200, 40);
        add(label2);

        // SECOND PART//Create second TextField to enter a new Password when changing Password
        tf3 = new JTextField();
        tf3.setBounds(50, 200, 150, 40);
        add(tf3);

        // SECOND PART//Create second button to take the changed Password and put it where the old password was
        JButton button3 = new JButton("Change Password");
        button3.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
            }
        });
        button3.setBounds(200, 200, 150, 30);
        add(button3);

        // THIRD PART//Create third button to display a existing password
        JButton button2 = new JButton("Display Password");
        button2.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                // DatabaseConnection con2 = new DatabaseConnection ();
                // con2.listPasswords();
            }
        });
        button2.setBounds(200, 250, 150, 30);
        add(button2);
    } // Konstruktur Ende

    public static void main(String args[]) {

        JFrame frame1 = new JFrame();
        frame1.setTitle("Password Saver");
        frame1.setSize(600, 600);
        frame1.setLocation(800, 200);
        frame1.setResizable(false);
        frame1.add(new JFrameFunctionality());
        frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame1.setVisible(true);
    }

    public class codeforButtons {

        Connection con1 = null;
        Connection con2 = null;
        PreparedStatement stat1 = null;
        Statement stat2 = null;
        ResultSet rs = null;

        public void getConnection() { // Establishes a connection to the database "passwords"
             try {
             Class.forName("org.sqlite.JDBC");
             con1 = DriverManager.getConnection("JDBC:sqlite:PasswordDatabase.sqlite");
             System.out.println("Connection established...");

             } catch (Exception e) {
             System.out.println("Error: " + " " + e.getMessage());
             }

        }

        public void insertSQLB1() { // Inserts the application name into the database *not working, inserts only a blank
            // row*
            try {
                 getConnection();
                 String query = "INSERT INTO passwords (Anwendung) VALUES (?)";
                 PreparedStatement stat1 = con1.prepareStatement(query);
                 stat1.setString(1, tf2.getText());
                 stat1.execute();
                 JOptionPane.showMessageDialog(null, "Data saved!");

                 con1.close();

            } catch (Exception e) {
                System.out.println("Error: " + e.getMessage());
            }

        }

        public void listPasswords() { // Gibt alle Passwörter aus der Datenbank aus und unterbricht dann die Verbindung
                                        // zur
                                        // DB
            try {
                getConnection();
                this.stat2 = con2.createStatement();
                ResultSet rs = stat1.executeQuery("SELECT * FROM passwords");

                while (rs.next()) {
                    String password = rs.getString("Passwort");
                    String program = rs.getString("Anwendung");

                    System.out.println("Passwort: " + password + " " + "Anwendung: " + program);
                }
            } catch (Exception e) {
                System.out.println("Error: " + e.getMessage());
            }

        }

    }

}

===

或者,从codeforButtons 中删除extends JFrameFunctionality,然后更改insertSQLB1 以接受字符串作为传入的参数。

public void insertSQLB1(String value) { // Inserts the application name into the database *not working, inserts only a blank
            // row*
            try {
                 getConnection();
                 String query = "INSERT INTO passwords (Anwendung) VALUES (?)";
                 PreparedStatement stat1 = con1.prepareStatement(query);
                 stat1.setString(1, value);
                 stat1.execute();
                 JOptionPane.showMessageDialog(null, "Data saved!");

                 con1.close();

            } catch (Exception e) {
                System.out.println("Error: " + e.getMessage());
            }

        }

然后把调用者改成

cfBobj1.insertSQLB1(tf2.getText());

通过这种方式,您将值传递到数据管理层,并在接口层和数据管理层之间实现更好的分离。

【讨论】:

  • 非常感谢您的快速答复!我会试试看:)
  • 你好,pfranza,
猜你喜欢
  • 1970-01-01
  • 2023-03-10
  • 1970-01-01
  • 1970-01-01
  • 2014-03-08
  • 1970-01-01
  • 1970-01-01
  • 2018-12-19
  • 1970-01-01
相关资源
最近更新 更多