| Accessing MySQL on NetBeans using JDBC, Part II: Perform SQL Operations |
From Part I, I have only established a connection with local MySQL. Next I’ll show how to retrieve and modify data on remote MySQL.
MySQL Connection using in this part
Suppose that I have MySQL running remotely on IP:192.168.1.101 with default port (3306) and I want to connect to Northwind database with username is ‘root’ and password is ‘123456’. The connection string will be
String connectionUrl = "jdbc:mysql://192.168.1.101:3306/Northwind?" + "user=root&password=123456";
Retrieve data from a database
To get some data, I need to execute query on the MySQL and get the result back to me. First, I create stmt (Statement object) and execute query in SQL language. Then I store the result on ResultSet object and iterative show the result on the output window.
Statement stmt = null; ResultSet rs = null; //SQL query command String SQL = "SELECT * FROM Products"; stmt = con.createStatement(); rs = stmt.executeQuery(SQL); while (rs.next()) { System.out.println(rs.getString("ProductName") + " : " + rs.getString("UnitPrice")); }
Code Explanation:
- Statement objects allow you to execute basic SQL queries and retrieve the results through the ResultSet class.
- In while-loop, iterative in the ResultSet object to show result in console (ProductName and UnitPrice columns in Products table) on output window.
The example result will be similar to below.
Note: I have imported only 4 records from Products table in Northwind database.

Update data on database
To insert, update and delete records on SQL Server, you can use the code from retrieve data from database and simply change SQL command and also modify some code a little bit. On update, I must use executeUpdate(�?SQL�?) method on statement object instead executeQuery(“SQL�?) and the return value will be rows affected instead of a record set.
Example
INSERT command
// SQL insert command String strSQL = "INSERT INTO Products (ProductName,QuantityPerUnit,UnitPrice,UnitsInStock,UnitsOnOrder," + "ReOrderLevel,Discontinued) VALUES ('MyProduct','10 Kg.',1234.0000,100,50,30,0)"; int rowsEffected = stmt.executeUpdate(strSQL); System.out.println(rowsEffected + " rows effected");
UPDATE command
// SQL update command String strSQL = "UPDATE Products SET UnitPrice = 900, UnitsInStock = 55, UnitsOnOrder = 5 WHERE ProductName = 'MyProduct'"; int rowsEffected = stmt.executeUpdate(strSQL); System.out.println(rowsEffected + " rows effected");
DELETE command
// SQL delete command String strSQL = "DELETE FROM Products WHERE ProductName = 'MyProduct'"); int rowsEffected = stmt.executeUpdate(strSQL); System.out.println(rowsEffected + " rows effected");
Summary
You can download source code example testMySQL.java (Right-click on the link and select Save target As…).
But you have to change connection string to match your environment. The example code will connect to Northwind database and try to retrieve records, insert a new record, update the record and delete the record from Products table. The result is below.


























April 23rd, 2008 at 10:24 am
Thanks a lot! That is exactly what I needed to get jump-started on Java & MySQL.
June 3rd, 2008 at 6:57 am
Very good.
You have no idea how hard it is to find a simple explanation like this.
June 11th, 2008 at 11:00 pm
can i ask u question
why i cannot build because of the con.
The result of the compiler is above
symbol : variable con
location: class test.test
stmt = con.createStatement();
1 error
BUILD FAILED (total time: 0 seconds)
who can help me !?
June 12th, 2008 at 8:46 am
I think that you haven’t completed part1: create a connection yet. You need to create a connection to MySQL before performing any query. Try to read part1 first.
June 15th, 2008 at 9:07 pm
Thanks a lot. i had solved my problem
June 19th, 2008 at 3:32 am
Thank you for this tutorial. Very usefull indeed. I have a problem with this line:
stmt = con.createStatement();
when I write it in my Netbeans IDE, it gets red underlined, the error message says: “Cannot find symbol”
Any idea why?
NB: on the following line:
Connection con = DriverManager.getConnection(connectionUrl);
The line is underlined grey saying that the con variable is not being used. That might be the source of the problem…
I import the followings:
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.ResultSet;
import java.sql.Connection;
and use IDE 6.1 and MySQL 5.1, connector 5.1.6
June 20th, 2008 at 10:31 pm
Hi, Arnaud
Normally, when you see this error message, it’ll tell which symbol. For instance,
cannot find symbol
symbol : variable aaa
location: class Main
This means that you haven’t declare a variable ‘aaa’ before using it.
According to your problem, have you already declare all of variables? Try check stmt and connectionUrl. In my example above, I have declare stmt = null and connectionUrl = “jdbc:mysql…..”.
June 23rd, 2008 at 9:01 pm
@Arnaud: You have to put the code of this part inside the scope of the “try” command from Part I.
If you place the code outside, then the compiler doesn’t see the declaration for the Connection con.
June 24th, 2008 at 9:17 pm
Thanks Dory, that was the answer to my problem. As I said very new to java programming.
Sorry that was very basic.
Thank you both for your answers.
By the way anybody knows where I could find a tutorial to then bind this query (INNER JOIN through more than 1 table) to a JTable?
The NetBeans tutorials only shows how to bind a simple table to a JTable, which is not very usefull as most of my tables contains ID’s we are of no meaning to the interface use.
Thank you
July 18th, 2008 at 1:31 pm
It’s great!!! I was trying to find out a place to start JAVA MYSQL connection and found no where. All the writers assume that only professionals have the right to read their articles.
Thanks a lot for the simple but great and effective article.
October 9th, 2008 at 12:39 pm
thnks a lot
it worked for me
October 25th, 2008 at 7:59 am
Nice Job.
Obrigado!!!
October 28th, 2008 at 8:09 pm
How to insert, update and delete if we use has map method?
Can you explain about it???
October 28th, 2008 at 8:59 pm
Hi, inD_05
What do you means “map method”?
November 20th, 2008 at 5:48 am
Hi, I have followed your examples (parts I & II) and it compiles fine, BUT when invoking:
DriverManager.getConnection(url, user, pass);
it returns an error that i cant resolve by now:
com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure
Last packet sent to the server was 0 ms ago.
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
at java.lang.reflect.Constructor.newInstance(Constructor.java:513)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:406)
…
can you enlighten me here? THANKS!
November 20th, 2008 at 6:35 am
solved it
some how the “:port/” part of the conn string was causing troubles.