简体   繁体   中英

How can I store the values(JTextField & JXDatePicker) into MySQL database?

Please help me to execute this program:

try{
  Connection conn;
    String dbuser = "root";
    String dbpassw = "1209";
    String databasename = "mynewdatabase";
    String url = "jdbc:mysql://localhost:3306/" + databasename;
    Class.forName("com.mysql.jdbc.Driver");
    conn = DriverManager.getConnection (url, dbuser, dbpassw);
    PreparedStatement ps = conn.prepareStatement("insert into newjframe1 values(?,?)");
    String TicketProjectSOWNo=jTextField1.getText().toString();
    String RELATED_REFERENCES=jTextField2.getText().toString();
    String REPORT_DATE=jXDatePicker3.getDate().toString();
    ResultSet res = ps.executeQuery(); 
    if (res.next()) {
        JOptionPane.showMessageDialog(this,"Data saved successfully");
    }  
}
catch( Exception e ) {
        System.out.println(e);
}

I tried like this but error comes when saving this components in the MySQL database. What is the right coding for this program?

You can edit your code like this

Assuming your table has 3 columns to be inserted

 PreparedStatement ps = conn.prepareStatement("insert into newjframe1 values(?,?,?)");

ps.setString(1,jTextField1.getText().toString());

ps.setString(2,jTextField2.getText().toString());

ps.setString (3,jXDatePicker3.getDate().toString());

int flag = ps.executeUpdate(); 
if (flag!=0) {

    JOptionPane.showMessageDialog(this,"Data saved successfully");
}  

Mistake you have done is not setting the place holder values for the PreparedStatement . Set the values into prepared statement using one of the .setXXX methods of prepared statement. Then it will save the data to the database.

Title of your question is misleading. You are not saving the swing component to the database. You are only saving the value. Please update the question title.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM