Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
215 views

A Java MySQL INSERT Example (Using PreparedStatement) - Java MySQL INSERT W - PreparedStatement - Alvinalexander

This document provides a Java MySQL INSERT example using a PreparedStatement. It includes: 1. Creating a sample MySQL database table with different data types. 2. The Java code to connect to the database, create a PreparedStatement with the INSERT query, set values for different data types, and execute the statement. 3. Verifying the data was inserted by querying the table and showing the new row. The example demonstrates how to insert a record into a MySQL database from Java using a PreparedStatement, including connecting to the database, setting values, and executing the statement.

Uploaded by

Vedansh Agrawal
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
215 views

A Java MySQL INSERT Example (Using PreparedStatement) - Java MySQL INSERT W - PreparedStatement - Alvinalexander

This document provides a Java MySQL INSERT example using a PreparedStatement. It includes: 1. Creating a sample MySQL database table with different data types. 2. The Java code to connect to the database, create a PreparedStatement with the INSERT query, set values for different data types, and execute the statement. 3. Verifying the data was inserted by querying the table and showing the new row. The example demonstrates how to insert a record into a MySQL database from Java using a PreparedStatement, including connecting to the database, setting values, and executing the statement.

Uploaded by

Vedansh Agrawal
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 5

20/7/2014 A Java MySQL INSERT example (using PreparedStatement) | Java MySQL INSERT w/ PreparedStatement | alvinalexander.

com
http://alvinalexander.com/java/java-mysql-insert-example-preparedstatement 1/5
my book at amazon
categories
android (45)
best practices (63)
career (50)
cvs (27)
design (33)
drupal (91)
eclipse (6)
funny (3)
gadgets (108)
git (15)
intellij (4)
java (429)
jdbc (26)
swing (74)
jsp (9)
latex (26)
linux/unix (289)
mac os x (315)
mysql (54)
ooa/ood (11)
perl (156)
php (97)
postgresql (17)
ruby (56)
scala (336)
sencha (23)
servlets (10)
A Java MySQL INSERT example (using PreparedStatement)
By Alvin Alexander. Last updated: Jun 12, 2014
Java MySQL INSERT example: Can you share a Java MySQL INSERT example, specifically using a Java
PreparedStatement object?
Sure. As the question implies, you can use the Java Statement class to issue a
MySQL INSERT statement, but the Java PreparedStatement class provides a much better way to insert
data into a MySQL database table. (You can learn more about the Java Statement class in this Using
SQL INSERT with Java Statement tutorial.
Java INSERT - An example MySQL database table
The first thing we'll need is an example MySQL database table. To keep it simple, but to also show
several different MySQL data types, I've created the following MySQL example database table:
A few of these MySQL fields are a little contrived, but I wanted to show several different data types in
one table, so this is what I came up with. In particular, the field "num_points" is a little weird. I made it
up so I could show a MySQL int data type in this table, and I was thinking of those websites where
points are awarded for giving correct answers.
Other than that, this MySQL database table is relatively normal, though it is greatly simplified.
Java MySQL INSERT PreparedStatement example - Source code
Given that MySQL database table design, let's assume that we just want to insert one record into this
MySQL table. To do so, we just need to follow these steps:
1. Create a Java Connection to our example MySQL database.
2. Create a SQL INSERT statement, using the Java PreparedStatement syntax.
3. Set the fields on our Java PreparedStatement object.
4. Execute a Java PreparedStatement .
5. Close our Java MYSQL database connection.
6. Catch any SQL exceptions that may come up during the process.
I've tried to document the following Java MySQL INSERT example so you can see these steps. Note that
in this example my MySQL database username is "root", my password is blank, and the MySQL
database is running on the same computer where this program is run, so the database host name is
"localhost".

create table users (
id int unsigned auto_increment not null,
first_name varchar(32) not null,
last_name varchar(32) not null,
date_created timestamp default now(),
is_admin boolean,
num_points int,
primary key (id)
);
import java.sql.*;
import java.util.Calendar;

/**
* A Java MySQL PreparedStatement INSERT example.
* Demonstrates the use of a SQL INSERT statement against a
* MySQL database, called from a Java program, using a
* Java PreparedStatement.
*
* Created by Alvin Alexander, <a href="http://devdaily.com" title="http://devdaily.com">http://devdaily.com
*/
public class JavaMysqlPreparedStatementInsertExample
{

20/7/2014 A Java MySQL INSERT example (using PreparedStatement) | Java MySQL INSERT w/ PreparedStatement | alvinalexander.com
http://alvinalexander.com/java/java-mysql-insert-example-preparedstatement 2/5
svn (6)
technology (84)
testing (13)
uml (24)
Java MySQL INSERT example - results
After running this Java MySQL INSERT example program, when you query your MySQL database table
like this:
you should see some output like this:
+----+------------+-----------+---------------------+----------+------------+
| id | first_name | last_name | date_created | is_admin | num_points |
+----+------------+-----------+---------------------+----------+------------+
| 1 | Barney | Rubble | 2010-06-23 14:02:00 | 0 | 5000 |
+----+------------+-----------+---------------------+----------+------------+
1 row in set (0.00 sec)
This shows that the Java MySQL INSERT PreparedStatement example worked properly.
Java MySQL INSERT example using PreparedStatement - summary
I hope this Java MySQL INSERT example (using a PreparedStatement ) makes sense as is. In "real
world" Java database programs I almost always use Spring to access a database, but when you're first
getting started, I think it's important to see examples like this so you can understand how things work
under the covers. This example specifically shows:
public static void main(String[] args)
{
try
{
// create a mysql database connection
String myDriver = "org.gjt.mm.mysql.Driver";
String myUrl = "jdbc:mysql://localhost/test";
Class.forName(myDriver);
Connection conn = DriverManager.getConnection(myUrl, "root", "");

// create a sql date object so we can use it in our INSERT statement
Calendar calendar = Calendar.getInstance();
java.sql.Date startDate = new java.sql.Date(calendar.getTime().getTime());

// the mysql insert statement
String query = " insert into users (first_name, last_name, date_created, is_admin, num_points)"
+ " values (?, ?, ?, ?, ?)";

// create the mysql insert preparedstatement
PreparedStatement preparedStmt = conn.prepareStatement(query);
preparedStmt.setString (1, "Barney");
preparedStmt.setString (2, "Rubble");
preparedStmt.setDate (3, startDate);
preparedStmt.setBoolean(4, false);
preparedStmt.setInt (5, 5000);

// execute the preparedstatement
preparedStmt.execute();

conn.close();
}
catch (Exception e)
{
System.err.println("Got an exception!");
System.err.println(e.getMessage());
}
}
}
select * from users;
20/7/2014 A Java MySQL INSERT example (using PreparedStatement) | Java MySQL INSERT w/ PreparedStatement | alvinalexander.com
http://alvinalexander.com/java/java-mysql-insert-example-preparedstatement 3/5
1. How to connect to a MySQL database.
2. How to create a Java Date object.
3. How to create a Java PreparedStatement with a SQL INSERT query.
4. How to set the fields on a variety of different data types.
5. How to execute the Java PreparedStatement .
6. One way to confirm that our data was successfully inserted into our MySQL database.
As usual, if you have any questions or comments about this Java MySQL INSERT example, just use the
Comment form below.
tags: database database table insert java java mysql preparedstatement sql sql insert statement
books i've written
related
A Java MySQL INSERT example (using Statement)
A Java MySQL UPDATE example
A Java MySQL DELETE example
A Java MySQL SELECT example
Java MySQL examples and tutorials
Java current date example - how to create a Java Date to represent the current time
new
How to turn off (disable) iOS AMBER alerts
Three free Savasana-like guided meditations (MP3 audio recordings)
Methods on the Scala collections classes, organized by category
20/7/2014 A Java MySQL INSERT example (using PreparedStatement) | Java MySQL INSERT w/ PreparedStatement | alvinalexander.com
http://alvinalexander.com/java/java-mysql-insert-example-preparedstatement 4/5
All comments Replies to my comment
Day 20 of the low iodine diet (before radioactive iodine treatment)
Complete backup scripts for my websites (Drupal, MySQL)
How to add a Sencha ExtJS splash (loading) screen
How I got the xdaliclock xscreensaver working on RPI/Debian
Notes on configuring Sencha Touch, Nginx, and Play on Mac OS X
Trying to tune Mac OS X 10.9 performance on an old Mac (purge command)
How to kill/disable the Dashboard in Mac OS X 10.9
more
alvin's blog
Post new comment
Your name:
Anonymous
E-mail:
The content of this f ield is kept private and will not be shown publicly.
Homepage:
Subject:
Comment: *
Notify me when new comments are posted
Preview

java
java applets
java faqs
misc content
java source code
test projects
lejos
perl
unix
man (help) pages
unix by example
tutorials
source
code
warehouse
java examples
drupal examples
misc
privacy policy
terms & conditions
subscribe
unsubscribe
wincvs tutorial
function point
analysis (fpa)
fpa tutorial
other
rss feed
my photos
life in alaska
how i sold my business
living in talkeetna, alaska
my bookmarks
inspirational quotes
source code snippets
20/7/2014 A Java MySQL INSERT example (using PreparedStatement) | Java MySQL INSERT w/ PreparedStatement | alvinalexander.com
http://alvinalexander.com/java/java-mysql-insert-example-preparedstatement 5/5
perl faqs
programs
perl recipes
perl tutorials

You might also like