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