2016-06-06 5 views
-1

Я ве работал над программой телефонной книги на затмение JavaКак сохранить данные в MySQL

но и ИДК, как сохранить информацию из textfield в mysql и затем иметь возможность использовать его в поиске, например, как писать имя и найти всю информацию о конкретном контакте Я также хочу, чтобы сохранить его в моей SQL тот мой код:

public class Phone { 

    private JFrame frame; 
    private JTextField firstfield; 
    private JTextField phonefield; 
    private JTextField emailfield; 
    private JTextField lastfield; 
    private JPanel MainScreen; 
    private JPanel newcontact; 
    private JPanel searchscreen; 



    /** 
    * Launch the application. 
    */ 
    public static void main(String[] args) { 
     EventQueue.invokeLater(new Runnable() { 
      public void run() { 
       try { 
        Phone window = new Phone(); 
        window.frame.setVisible(true); 
       } catch (Exception e) { 
        e.printStackTrace(); 
       } 
      } 
     }); 
    } 

    /** 
    * Create the application. 
    */ 
    public Phone() { 
     initialize(); 
    } 

    /** 
    * Initialize the contents of the frame. 
    */ 
    private void initialize() { 
     frame = new JFrame(); 
     frame.setBounds(100, 100, 450, 300); 
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     frame.getContentPane().setLayout(new CardLayout(0, 0)); 

     final JPanel MainScreen = new JPanel(); 
     frame.getContentPane().add(MainScreen, "name_6058038854379"); 
     MainScreen.setLayout(null); 
     MainScreen.setVisible(true); 

     final JPanel newcontact = new JPanel(); 
     newcontact.setLayout(null); 
     frame.getContentPane().add(newcontact, "name_791613670731"); 
     newcontact.setVisible(false); 

     final JPanel searchscreen = new JPanel(); 
     frame.getContentPane().add(searchscreen, "name_6068807854350"); 
     searchscreen.setVisible(false); 


     JButton newrecord = new JButton("New Record"); 
     newrecord.addActionListener(new ActionListener() { 
      public void actionPerformed(ActionEvent arg0) { 
       newcontact.setVisible(true); 
       MainScreen.setVisible(false); 

      } 
     }); 
     newrecord.setBounds(63, 99, 116, 52); 
     MainScreen.add(newrecord); 

     JButton Search = new JButton("Search"); 
     Search.addActionListener(new ActionListener() { 
      public void actionPerformed(ActionEvent e) { 
       searchscreen.setVisible(true); 
       newcontact.setVisible(false); 
      } 
     }); 
     Search.setBounds(243, 99, 102, 52); 
     MainScreen.add(Search); 

     JLabel myphonebook = new JLabel(" My Phonebook"); 
     myphonebook.setBounds(162, 44, 102, 14); 
     MainScreen.add(myphonebook); 



     JLabel first = new JLabel("First Name:"); 
     first.setBounds(118, 83, 66, 14); 
     newcontact.add(first); 

     JLabel last = new JLabel("Last Name:"); 
     last.setBounds(118, 108, 66, 14); 
     newcontact.add(last); 

     JLabel Phone = new JLabel("Phone:"); 
     Phone.setBounds(118, 143, 66, 14); 
     newcontact.add(Phone); 

     JLabel Emailadress = new JLabel("Email Adress:"); 
     Emailadress.setBounds(118, 180, 66, 14); 
     newcontact.add(Emailadress); 

     firstfield = new JTextField(); 
     firstfield.setColumns(10); 
     firstfield.setBounds(220, 80, 86, 20); 
     newcontact.add(firstfield); 

     lastfield = new JTextField(); 
     lastfield.setColumns(10); 
     lastfield.setBounds(220, 108, 86, 20); 
     newcontact.add(lastfield); 



     phonefield = new JTextField(); 
     phonefield.setColumns(10); 
     phonefield.setBounds(220, 140, 86, 20); 
     newcontact.add(phonefield); 


     emailfield = new JTextField(); 
     emailfield.setColumns(10); 
     emailfield.setBounds(220, 177, 86, 20); 
     newcontact.add(emailfield); 



     JLabel lblNewContact = new JLabel("New Contact"); 
     lblNewContact.setBounds(166, 30, 86, 14); 
     newcontact.add(lblNewContact); 

     JButton Save = new JButton("Save"); 
     Save.addActionListener(new ActionListener() { 
      public void actionPerformed(ActionEvent arg0) { 
       String firstname=firstfield.getText(); 
       String lastname=lastfield.getText(); 
       String phonenumber=phonefield.getText(); 
       String emailadress=emailfield.getText(); 



      } 
     }); 
     Save.setBounds(81, 232, 89, 23); 
     newcontact.add(Save); 

     JButton cancel = new JButton("Cancel"); 
     cancel.addActionListener(new ActionListener() { 
      public void actionPerformed(ActionEvent e) { 
       newcontact.setVisible(false); 
       MainScreen.setVisible(true); 
      } 
     }); 
     cancel.setBounds(283, 232, 89, 23); 
     newcontact.add(cancel); 



     JPanel panel_1 = new JPanel(); 
     frame.getContentPane().add(panel_1, "name_6081212161880"); 
    } 
} 
+0

Это интересный проект, сообщите нам, если у вас есть вопрос! – Shadow

+0

эй @ Shadow У меня вопрос. Я отчасти новичок в программировании, и я хотел знать, если prepareStmt.execute(); принесут информацию mysql и покажут ее в программе – Beginnerprogrammer

ответ

0

Записать это в вашем savecommand. Вы должны создать таблицу базы данных и изменить слова в верхнем регистре.

try 
     { 
      // create a mysql database connection 
      String myDriver = "org.gjt.mm.mysql.Driver"; 
      String myUrl = "jdbc:mysql://LOCATION/DATABASE"; 
      Class.forName(myDriver); 
      Connection conn = DriverManager.getConnection(myUrl, "root", ""); 

      // create a sql date object so we can use it in our INSERT statement 
      Calendar calendar = Calendar.getInstance(); 
      java.sql.Date startDate = new java.sql.Date(calendar.getTime().getTime()); 

      // the mysql insert statement 
      String query = " insert into TABLE (first_name, last_name, phone_number, email_adress)" 
      + " values (?, ?, ?, ?)"; 

      // create the mysql insert preparedstatement 
      PreparedStatement preparedStmt = conn.prepareStatement(query); 
      preparedStmt.setString (1, firstname); 
      preparedStmt.setString (2, lastname); 
      preparedStmt.setString (3, phonenumber); 
      preparedStmt.setString (4, emailadress); 

      // execute the preparedstatement 
      preparedStmt.execute(); 

      conn.close(); 
     } 
     catch (Exception e) 
     { 
      System.err.println("Got an exception!"); 
      System.err.println(e.getMessage()); 
     } 
     } 
+0

, поэтому я помещаю ее под действие инициатора сохранения кнопки сохранения и ее работу? – Beginnerprogrammer

+0

его ошибка, потому что PreparedStatement и Calendar и Connection могут быть разрешены к типу, и DriverManager не может быть разрешен во всех случаях plz help @ Matti9811 – Beginnerprogrammer

+0

ОК, так что это сработало, но я получил исключение, и этот код org.gjt.mm.mysql.Driver – Beginnerprogrammer