简体   繁体   中英

Java: Adding new record to database using prepare statement

I'm working on a Java project using the NetBeans GUI generator and Derby. I'm having trouble adding a new record to a database table using a button and text field.

The ActionPerformed for the button being used extracts the input from the text field, and sends it to the addCustomer method inside the customer class. Below is the code for the customer class and the addCustomer method. The class also calls a separate class, DBConnection, that establishes a connection to the database.

I'm fairly new to working with databases in Java, so any help and guidance would be greatly appreciated.

public class Customer extends DBConnection
{
private PreparedStatement insertNewCustomer;
private PreparedStatement allCustomers;

//Customer Class Constructor
public Customer()
{
    getConnection();
    try
    {
        insertNewCustomer = connection.prepareStatement("INSERT INTO Customer" + "Name" + "VALUES (?)");
        allCustomers = connection.prepareStatement("SELECT * FROM Customer");
    }
    catch (SQLException sqlException)
    {
        sqlException.printStackTrace();
        System.exit(1);
    }  
}
//End of constructor

//Adds a new customer to the CUSTOMER table in the database
public void addCustomer(String newName)
{
    try {
        insertNewCustomer.setString(1,newName);
        insertNewCustomer.executeUpdate();
    }
    catch (SQLException sqlException) 
    {
        sqlException.printStackTrace();
    }
}

The insert SQL Syntax is incorrect that you have passed to prepareStatement. It is possible to write the INSERT INTO statement in two ways.

INSERT INTO table_name (column1, column2, column3, ...)
VALUES (value1, value2, value3, ...);

If you are adding values for all the columns of the table, you do not need to specify the column names in the SQL query.

INSERT INTO table_name
VALUES (value1, value2, value3, ...);

I assume Customer is your table name then the correct syntax in your case is

 insertNewCustomer = connection.prepareStatement
 ("INSERT INTO Customer VALUES (?)");

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