I'm making a GUI. Which can insert data when user click JButton b1. The back-end database has 1 table which is movies and has two columns.The name of 1st column is title and data type is varchar and 2nd column name is year which has data type integer.But i don't know how to write this query in program with the help of text fields. I try many codes on query but nothing happend.
Code:
public class A extends JFrame{
private JTextField t1;
private JTextField t2;
private JLabel l1;
private JLabel l2;
private JButton b1;
private Connection conn;
private Statement state;
String server = "jdbc:mysql://localhost/demo";
String user="root";
String pass="65";
public A(){
super("Query");
setLayout(null);
t1= new JTextField();
t1.setBounds(173, 152, 128, 27);
add(t1);
//for year
t2= new JTextField();
t2.setBounds(173, 105, 128, 27);
add(t2);
l1= new JLabel("title");
l1.setBounds(99, 101, 42, 37);
add(l1);
l1= new JLabel("year");
l1.setBounds(99, 148, 42, 37);
add(l1);
b1= new JButton("Insert");
b1.setBounds(50, 222, 102, 37);
add(b1);
b1.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
try{
CreateQuery("insert into movies (title,year) values('"+t1.getText()+"') ");
}
catch(Exception e1){
e1.printStackTrace();
}
}
});
setSize(450,450);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setResizable(false);
setVisible(true);
}
public void CreateQuery(String w){
try{
Class.forName("com.mysql.jdbc.Driver");
conn=DriverManager.getConnection(server,user,pass);
state = conn.createStatement();
state.executeUpdate(w);
JOptionPane.showMessageDialog(null, "Query Executed");
}
catch(Exception e){
JOptionPane.showMessageDialog(null, e.getMessage());
}
}
}
Main:
public class Main {
public static void main(String[] args) {
A obj = new A();
}
}
You can do this in two ways, First one is the procedure you are using, i.e. using createStatement
In your case you have to set both title and year.
CreateQuery("insert into movies (title,year) values('"+t1.getText()+"', " + t2.getText() + ")");
And the second one is using preparedStatement, Method calling,
CreateQuery(t1.getText(), t2.getText());
Method,
public void CreateQuery(String title, String year){
try{
Class.forName("com.mysql.jdbc.Driver");
conn=DriverManager.getConnection(server,user,pass);
PreparedStatement state = conn.prepareStatement("insert into movies (title,year) values('?', ?)");
state.setString(1, title);
state.setInt(1, new Integer(year));
state.executeUpdate();
JOptionPane.showMessageDialog(null, "Query Executed");
}
catch(Exception e){
JOptionPane.showMessageDialog(null, e.getMessage());
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With