Witam serdecznie. Chciałem napisać prostą aplikację zapisującą dane z formularza do bazy MySQL. Przykład jest z książki eksperta, różnych modyfikacji próbowałem i nic. Problemem chyba nie jest baza tylko sam kod zapisu do niej.
public class Zapis {
public static void main (String args[]){
Okno okno=new Okno();
}
}
class Okno extends JFrame{
public Okno(){
setSize(400, 400);
setTitle("Dodawanie rekordów do bazy Auta");
Panel panel=new Panel();
getContentPane().add(panel);
setDefaultCloseOperation(3);
setVisible(true);
}
}
class Panel extends JPanel implements ActionListener{
JTextField pole1, pole2,pole3;
JButton przycisk;
JLabel wiadomosc=new JLabel("");
Statement st;
public Panel(){
setBackground(new Color(200,151,255));
pole1=new JTextField(15);
pole2=new JTextField(15);
pole3=new JTextField(15);
add(new JLabel("Marka:"));
add(pole1);
add(new JLabel("Model:"));
add(pole2);
add(new JLabel("Kolor:"));
add(pole3);
przycisk=new JButton("Dodaj Samochód");
przycisk.addActionListener(this);
add(przycisk);
add(wiadomosc);
}
@Override
public void actionPerformed(ActionEvent arg0) {
polacz();
String s1=pole1.getText().trim();
String s2=pole2.getText().trim();
String s3=pole3.getText().trim();
String polecenie="INSERT INTO Auta(marka,model,kolor) values('"+s1+"','"+s2+"','"+s3+"')";
try{
st.executeUpdate(polecenie);
st.close();
}catch (Exception ek){}
wiadomosc.setText("Auto zostało dodane");
pole1.setBackground(Color.yellow);
pole2.setBackground(Color.yellow);
pole3.setBackground(Color.yellow);
validate();
}
public void polacz(){
try{
Class.forName("com.mysql.jdbc.Driver");
Connection conexion = DriverManager.getConnection("jdbc:mysql://localhost/Auta", "Benon", "majster");
Statement st = conexion.createStatement();
System.out.println("Polaczenie istnieje.");
}catch (Exception ek){
System.out.println("Brak polaczenia.");
}
}
}
**Dodawanie rekordów działa w ten sposób, ale on nie jest zbyt dobry. **
public class Main {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection conexion = DriverManager.getConnection("jdbc:mysql://localhost/Auta", "Benon", "majster");
Statement st = conexion.createStatement();
st.executeUpdate("Insert into Auta (marka,model,kolor) values ('Star','125','Niebieski')");
ResultSet rs = st.executeQuery("select marka, model, kolor from Auta");
while(rs.next()){
System.out.println(rs.getString("marka")+"\t"+rs.getString("model")+"\t"+rs.getString("kolor"));
}
}catch (Exception e){
System.out.println(e);
}
}
}
Pomóżcie muszę to jutro oddać na zaliczenie.