0

I cannot save the input into my database. Can anybody help me? There's SSL problem but it is able to solve by setting SSL to false, but the data seems like only able to read but not save into my database.

package first;

import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.Connection;
import javax.swing.JOptionPane;

public class CustomersForm extends javax.swing.JFrame {
    public CustomersForm() {
        initComponents();
    }

    private void jButton_addcusActionPerformed(java.awt.event.ActionEvent evt) {
        // TODO add your handling code here:
        try {
            Class.forName("com.mysql.jdbc.Driver");
            String connectionURL = "jdbc:mysql://localhost:3308/java_his_db";
            Connection con = DriverManager.getConnection(connectionURL, "root", "");
            String sql = "Insert into customers ('fname') values (?)";
            PreparedStatement ps = con.prepareStatement(sql);
            ps.setString(2, jTextField_fname.getText());
            ps.executeUpdate();
            System.out.println("YES");
            con.close();
        }
        catch(Exception e){
            JOptionPane.showMessageDialog(rootPane, "Blank or Wrong User Profile", "Insert Error", 2);
        }  
    }                                                         

    private void jTextField_fnameActionPerformed(java.awt.event.ActionEvent evt) {                                                 
        // TODO add your handling code here:
    }
Abra
  • 19,142
  • 7
  • 29
  • 41
Nash
  • 29
  • 1
  • 5
  • 2
    Add the following line to the `catch` block in method `jButton_addcusActionPerformed`: `e.printStackTrace()`. Then run your program. Then [edit] your question and post the entire stack trace and error message. – Abra Jan 23 '21 at 06:29
  • You said "SSL problem". Do you mean "SQL problem"? – Basil Bourque Jan 23 '21 at 06:48

2 Answers2

1

You have only one placeholder in your query, therefore in this statement the index should be one: ps.setString(1, jTextField_fname.getText());

Andrew Vershinin
  • 1,958
  • 11
  • 16
  • but it still shows the exception message :( – Nash Jan 23 '21 at 06:18
  • 1
    @Nash What exception? – Andrew Vershinin Jan 23 '21 at 06:25
  • 1
    Hint: the SQL string is wrong (in the original question) – Abra Jan 23 '21 at 06:30
  • @Andrew it shows "Blank or Wrong User Profile" – Nash Jan 23 '21 at 06:34
  • @Abra the origin SQL string was longer, I was just trying for one text field first coz when I run in the full string it was unable to run. – Nash Jan 23 '21 at 06:36
  • 1
    @Nash `'fname'` is a string literal in SQL and not the name of a column in database table `customers`. Did you read my [comment](https://stackoverflow.com/questions/65856233/why-my-data-cannot-be-insert-into-database#comment116438862_65856233) to your question? If you want an answer that solves your problem, then you need to provide **all** the details regarding the exception you claim to be getting. – Abra Jan 23 '21 at 06:51
1

The Answer by Andrew Vershinin looks correct. Your placeholder number 2 should be 1.

You commented that you still have errors, but neglected to describe those errors. The errors might be from your SQL for the INSERT statement. You should not make a string of the column name. You put single-quotes where they do not belong. As commented by Abra, this single quotes around 'fname' makes that text into a string literal rather than the name of a column. A string literal makes no sense in SQL where a column name is expected.

Your code:

String sql = "Insert into customers ('fname') values (?)";

…should be:

String sql = "INSERT INTO customers ( fname ) values (?) ;";

In my example below, you will see similar code:

INSERT INTO person_ ( name_ )
VALUES ( ? )
;

Here is an entire example app that creates a database with one table person_, inserts two rows in that table, and retrieves those two rows. You can see how calling PreparedStatement#set… methods works.

This code uses the H2 Database Engine. But the following code will be nearly the same for any SQL database.

Tip: Separate your database access code from your GUI code. Get that database code worked out and running smoothly before trying to integrate with GUI.

Tip: Use try-with-resources to automatically close your connection, statement, result set, and so on.

Tip: Always include the optional semicolon statement terminator. You can get away without it in some places, but could mess up code in other places. Be neat, be consistent.

package work.basil.example;

import com.thedeanda.lorem.LoremIpsum;
import org.h2.jdbcx.JdbcDataSource;

import javax.sql.DataSource;
import java.sql.*;
import java.time.Instant;
import java.time.OffsetDateTime;
import java.util.Objects;

public class DbH2Example
{
    public static void main ( String[] args )
    {
        DbH2Example app = new DbH2Example();
        app.demo();
    }

    private void demo ( )
    {
        // -------------------|  DataSource  |---------------------------------
        DataSource dataSource = null;
        {
            org.h2.jdbcx.JdbcDataSource ds = Objects.requireNonNull( new JdbcDataSource() );  // Implementation of `DataSource` bundled with H2.
            ds.setURL( "jdbc:h2:mem:MyExampleDb;DB_CLOSE_DELAY=-1" );  // To keep an in-memory database after disconnecting, add DB_CLOSE_DELAY=-1 argument.
            ds.setUser( "scott" );
            ds.setPassword( "tiger" );
            ds.setDescription( "An example database showing how to insert a row." );
            dataSource = ds;
        }
        Objects.requireNonNull( dataSource );

        // -------------------|  Prepare database  |---------------------------------
        {
            String sql =
                    """
                    DROP TABLE IF EXISTS person_ 
                    ;
                    CREATE TABLE IF NOT EXISTS person_
                    (
                        name_ text NOT NULL  ,
                        row_created_ TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP() ,
                        id_ IDENTITY NOT NULL ,
                        CONSTRAINT person_pkey_ PRIMARY KEY ( id_ )
                    )
                    ;
                    """;
            try (
                    Connection conn = dataSource.getConnection() ;
                    Statement stmt = conn.createStatement() ;
            )
            {
                System.out.println( "INFO - Preparing database. Message # adaaf8ed-8922-4c15-addf-35f6ead1442b. " + Instant.now() );
                stmt.executeUpdate( sql );
            }
            catch ( SQLException e )
            {
                e.printStackTrace();
            }
        }

        // -------------------|  Insert row  |---------------------------------
        {
            System.out.println( "INFO - Insert rows. Message # 7a7e1c0a-7e97-4ebc-8d24-6e9ea20f8b5f. " + Instant.now() );
            String sql =
                    """
                    INSERT INTO person_ ( name_ )
                    VALUES ( ? )
                    ;
                    """;
            try
                    (
                            Connection conn = dataSource.getConnection() ;
                            PreparedStatement ps = conn.prepareStatement( sql ) ;
                    )
            {
                ps.setString( 1 , "Alice" );
                ps.executeUpdate();

                ps.setString( 1 , "Bob" );
                ps.executeUpdate();
            }
            catch ( SQLException e )
            {
                e.printStackTrace();
            }
        }

        // -------------------|  Dump rows  |---------------------------------
        {
            System.out.println( "INFO - Dump rows. Message # f6b786be-ef1e-4b97-9779-59bc84566e3d. " + Instant.now() );
            try
                    (
                            Connection conn = dataSource.getConnection() ;
                            Statement stmt = conn.createStatement() ;
                    )
            {
                String sql =
                        """
                        TABLE person_
                        ;
                        """;
                try (
                        ResultSet rs = stmt.executeQuery( sql ) ;
                )
                {
                    while ( rs.next() )
                    {
                        String name = rs.getString( "name_" );
                        Instant whenCreated = rs.getObject( "row_created_" , OffsetDateTime.class ).toInstant();
                        long id = rs.getLong( "id_" );
                        System.out.println( "whenCreated = " + whenCreated + " | " + "id : " + id + " | " + "name = " + name );
                    }
                }
            }
            catch ( SQLException e )
            {
                e.printStackTrace();
            }
        }
    }
}

When run.

INFO - Preparing database. Message # adaaf8ed-8922-4c15-addf-35f6ead1442b. 2021-01-23T06:44:22.363589Z
INFO - Insert rows. Message # 7a7e1c0a-7e97-4ebc-8d24-6e9ea20f8b5f. 2021-01-23T06:44:22.389564Z
INFO - Dump rows. Message # f6b786be-ef1e-4b97-9779-59bc84566e3d. 2021-01-23T06:44:22.414178Z
whenCreated = 2021-01-23T06:44:22.393600Z | id : 1 | name = Alice
whenCreated = 2021-01-23T06:44:22.413983Z | id : 2 | name = Bob
Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
  • Now I get it! It was the string error, i have been too extra to add those quotes around the input – Nash Jan 23 '21 at 07:53