How do I insert a record into database table?

Category: java.sql, viewed: 6987 time(s).

In this example you'll learn how to create a program to insert data into a database table. To insert a data we need to get connected to a database. After a connection is obtained you can create a java.sql.Statement object from it, and using this object we can execute some query string.

package org.kodejava.sample.java.sql;
 
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import java.sql.SQLException;
 
public class SelectStatementSample
{
    public static void main(String[] args) throws Exception
    {
        Connection connection = null;
        try
        {
            // Register MySQL JDBC driver to be known by 
            // the DriverManager object.
            Class.forName("com.mysql.jdbc.Driver");
 
            // Get a connection to database. We prepare the 
            // connection information here such as database 
            // url, user and password.
            String url = "jdbc:mysql://localhost/testdb";
            String user = "root";
            String password = "";
            connection = DriverManager.getConnection(url, 
                user, password);
 
            // Create a statement object instance from the 
            // connection
            Statement stmt = connection.createStatement();
 
            // We are going to execute an insert statement. 
            // First you have to create a table that has an 
            // ID, NAME and ADDRESS field. For ID you can use 
            // an auto number, while NAME and ADDRESS are 
            // VARCHAR fields.
            String sql = "INSERT INTO users (name, address) " +
                    "VALUES ('Foo Bar', 'Some Street')";
 
            // Call an execute method in the statement object 
            // and passed the sql or query string to it.
            stmt.execute(sql);
 
            // After this statement is executed you'll have a 
            // record in your users table.
        } catch (ClassNotFoundException e)
        {
            System.err.println("Could not load database driver!");
        } catch (SQLException e)
        {
            e.printStackTrace();
        } finally
        {
            if (connection != null)
            {
                connection.close();
            }
        }
    }
}
Click here to lend your support to: Kode Java Org and make a donation at www.pledgie.com !

 

Uncensored Newsgroups
Download Hundreds of Complimentary Industry Resources

Get hundreds of popular Industry magazines, white papers, webinars, podcasts, and more; all available at no cost to you. With more than 600 complimentary offers, you'll find plenty of titles to suit your professional interests and needs. Click Here and Sign up today!

Java Training

Sponsored Links

Our Friends

Statistics

Locations of visitors to this page
visitor stats