Java JDBC - Inserting a Record Example

This program adds a customer into a NorthWind-like database.

The example demonstrates the use of prepared statements and SQL INSERT calls.

To run this example against a MySQL database you would do:

/path/to/java
-Djdbc.drivers=com.mysql.jdbc.Driver
-classpath .:mysql-connector-java-3.1.8-bin.jar
AddCustomer
"jdbc:mysql://my.server.com:3306/Northwind?user=myuser&password=mypassword"

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
public class AddCustomer {
    public static void main(String[] args) {
        // check for the required command-line arguments
        if (args.length < 3) {
            System.err.println(Usage: AddCustomer <url> <customer-id>
                    + <company-name> <contact-name> <contact-title>
                    + <address> <city> <region> <postal-code>
                    + <country> <phone> <fax>);
            System.exit(1);
        }
        // the the a values
        String url = args[0];
        try {
            // Connect to the database
            Connection con = DriverManager.getConnection(url);
            try {
                // define the SQL INSERT statement
                String sql = INSERT INTO Customers VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);
                // prepare the statement
                PreparedStatement stmt = con.prepareStatement(sql.toString());
                // add the customer parameters (marked with ?)
                for (int i = 1; i < args.length; i++) {
                    stmt.setString(i, args[i]);
                }
                // run the SQL statement
                int result = stmt.executeUpdate();
                if (result == 0) {
                    System.out.println(Customer not added.);
                } else {
                    System.out.println(Customer added.);
                }
                stmt.close(); // release the statement
            } finally {
                con.close(); // release the connection
            }
        } catch (Exception e) {
            e.printStackTrace(); // "handle" errors
        }
    }
}

4 Responses to “Java JDBC - Inserting a Record Example”

  1. Coustorkito Says:

    Заметил такую тенденцию, что в блогах появилось много не адекватных комментариев, не могу понять, это что кто то спамит так? А зачем, чтоб падлу комуто сделать))) Имхо глупо…

  2. nati Says:

    hi
    i am nati from A.A Ethiopia
    thanks a lot for the things on this site esp jdbc.
    but can you please send me the full source code of the record keeping system.

  3. Любитель КВН Says:

    Интересно написано. Добавил в закладки kvnportal.ru =) Чмок, целую

  4. квн пельмени Says:

    Все, выхожу 15 ноября замуж. Поздравьте меня! Заходить теперь к вам редко буду.

Leave a Reply