| Accessing SQL Server on NetBeans using JDBC, Part II: Perform SQL Operations |
From Part I, I have only established a connection with local SQL Server. Next I’ll show how to retrieve and modify data on remote SQL Server.
There are 3 parts:
- Part I : Create a connection
This part which you’re reading shows about how to establish a connection between NetBeans and SQL Server. In this example, I use SQL Server 2000 SP4 and NetBeans IDE 5.5 - Part II : Perform SQL Operations
This part show how to perform some basic operations from NetBeans with SQL Server. For instance, send querys as SELECT, INSERT, UPDATE to the database. - Part III: Troubleshooting
The last part is about problems and how to fix them.
SQL Server Connection using in this part
Assume that I have SQL Server running remotely on BKKPDC01 computer and I want to connect to Northwind database with username is ‘sa’ and password is ‘password’. The connection string will be
String connectionUrl = "jdbc:sqlserver://bkkpdc01:1433;databaseName=Northwind;user=sa;password=password";
Retrieve data from database
To get some data, I need to execute query on the SQL Server 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 object is used for sending SQL Statement to the database.
- ResultSet object is used to keep data from the executed query.
- In while-loop, iterative in the ResultSet object to show result (All ProductName and UnitPrice in Products table) on output window.
The example result will be similar to below.
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 query command String SQL = "INSERT INTO Products (ProductName,QuantityPerUnit,UnitPrice,UnitsInStock,UnitsOnOrder,ReOrderLevel,Discontinued) VALUES ('MyProduct','10 Kg.',1234.0000,100,50,30,0)"; int rowsEffected = stmt.executeUpdate(SQL); System.out.println(rowsEffected + " rows effected");
UPDATE command
// SQL query command String SQL = "UPDATE Products SET UnitPrice = 900, UnitsInStock = 55, UnitsOnOrder = 5 WHERE ProductName = 'MyProduct'"; int rowsEffected = stmt.executeUpdate(SQL); System.out.println(rowsEffected + " rows effected");
DELETE command
// SQL query command String SQL = "DELETE FROM Products WHERE ProductName = 'MyProduct'"); int rowsEffected = stmt.executeUpdate(SQL); System.out.println(rowsEffected + " rows effected");
Summary
You can download the source code example here (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.




























August 18th, 2007 at 1:36 pm
Another great one.
Thank you very much
September 5th, 2007 at 8:25 pm
Hi again
Perfect…
Grettings!
September 21st, 2007 at 8:41 pm
When I try example I it works but the variable “con” is shown with a line under it.
when I try example II I get an error:
………\NetBeansProjects\TestSQL\src\testsql\Main.java:39: cannot find symbol
symbol : variable con
location: class testsql.Main
stmt = con.createStatement();
What am I doing wrong?
I use NetBeans 6 and SQL 2000
September 22nd, 2007 at 12:13 am
I think you haven’t declare variable con yet. I should be a Connection class. Try to review from my source code, I declared as a global variable.
September 29th, 2007 at 10:54 pm
very helpfull, it works but I don´t get the results on the output window (profiler shows the select is happening in the database)
src:
package testsql;
import java.sql.*;
/**
* @author Linglom
*/
public class testsql {
private static Statement stmt = null;
private static ResultSet rs = null;
private static Connection con = null;
public static void main(String[] args) {
try {
Class.forName(”com.microsoft.sqlserver.jdbc.SQLServerDriver”);
/* Connection string to connect to a remote server.
* Change the information to match your environment(hostname:port, username and password).
*/
String connectionUrl = “jdbc:sqlserver://localhost:1433;” +
“databaseName=visual_ftlhn;user=jboni0;password=exegis19740427″;
con = DriverManager.getConnection(connectionUrl);
stmt = con.createStatement();
retriveData(”SELECT * FROM pla_inn_ingresos where inn_codcia = 634 and inn_codpla = 20073009″);
int rowsEffected = 0;
// // Example INSERT new record
// rowsEffected = updateData(”INSERT INTO Products (ProductName,QuantityPerUnit,UnitPrice,UnitsInStock,UnitsOnOrder,” +
// “ReOrderLevel,Discontinued) VALUES (’MyProduct’,'10 Kg.’,1234.0000,100,50,30,0)”);
// System.out.println(rowsEffected + ” rows effected”);
// System.out.print(”Insert new record : “);
// retriveData(”SELECT * FROM Products WHERE ProductName = ‘MyProduct’”);
//
// // Example UPDATE the record
// rowsEffected = updateData(”UPDATE Products SET UnitPrice = 900, UnitsInStock = 55, UnitsOnOrder = 5″ +
// “WHERE ProductName = ‘MyProduct’”);
// System.out.println(rowsEffected + ” rows effected”);
// System.out.print(”Update the record : “);
// retriveData(”SELECT * FROM Products WHERE ProductName = ‘MyProduct’”);
//
// // Example DELETE the record
// rowsEffected = updateData(”DELETE FROM Products WHERE ProductName = ‘MyProduct’”);
// System.out.println(rowsEffected + ” rows effected”);
// System.out.print(”Delete the record”);
// retriveData(”SELECT * FROM Products WHERE ProductName = ‘MyProduct’”);
} catch (SQLException sqlEx) {
System.out.println(”SQL Exception: “+ sqlEx.toString());
} catch (ClassNotFoundException classEx) {
System.out.println(”Class Not Found Exception: “+ classEx.toString());
} catch (Exception Ex) {
System.out.println(”Exception: “+ Ex.toString());
}
}
/* Update data on the database
*@param SQL an update commandstring (INSERT, DELETE, UPDATE)
*/
public static int updateData(String SQL) throws Exception {
return stmt.executeUpdate(SQL);
}
/* Show result on output window
@param SQL a retrive data command string (SELECT)
*/
public static void retriveData(String SQL) throws Exception {
rs = stmt.executeQuery(SQL);
while (rs.next()) {
System.out.println(rs.getString(”inn_codcia”) + rs.getString(”inn_codtpl”) +
rs.getString(”inn_codpla”) + rs.getString(”inn_codemp”) +
rs.getString(”inn_codtig”) + rs.getString(”inn_valor”) +
rs.getString(”inn_dias”) + rs.getString(”inn_hora_dia”));
}
}
}
September 30th, 2007 at 2:26 am
ha ha ha… I´m Sorry my select statement was no returning rows :).
Very good example, thank you
October 27th, 2007 at 6:40 pm
It works perfectly fine;
the Article desciption was quite lucid n explanatory.
thnkz a lot frnd;
November 15th, 2007 at 1:14 am
Thank you so much for this..! But I am having a problem with an SQL exception and i dont know whats wrong.. Please help me out.. Here is the code:
public class testsql {
private static Statement stmt = null;
private static ResultSet rs = null;
private static Connection con = null;
public static void main(String[] args) {
try {
Class.forName(”com.microsoft.sqlserver.jdbc.SQLServerDriver”);
/* Connection string to connect to a remote server.
* Change the information to match your environment(hostname:port, username and password).
*/
String connectionUrl = “jdbc:sqlserver://lucero:1433;” +
“databaseName=dbBookone”;
con = DriverManager.getConnection(connectionUrl);
stmt = con.createStatement();
retriveData(”SELECT * FROM tblLogin”);
} catch (SQLException sqlEx) {
System.out.println(”SQL Exception: 1″+ sqlEx.toString()+”1″);
} catch (ClassNotFoundException classEx) {
System.out.println(”Class Not Found Exception: 2″+ classEx.toString()+”2″);
} catch (Exception Ex) {
System.out.println(”Exception: 3″+ Ex.toString()+”3″);
}
}
public static void retriveData(String SQL) throws Exception {
rs = stmt.executeQuery(SQL);
while (rs.next()) {
System.out.println(rs.getString(”UserName”));
}
}
}
Here is the exception:
SQL Exception: 1com.microsoft.sqlserver.jdbc.SQLServerException: The TCP/IP connection to the host has failed. java.net
.ConnectException: Connection refused: connect1
the “connect” option is enabled in the SQL server
Really dont know what to do..
November 16th, 2007 at 5:06 pm
To Jason,
The problem can occurs by 2 causes.
1. You have mistyped hostname or port number for the SQL server in the conectionUrl string so check the name again.
2. You try to connect to remote SQL server which hasn’t enable the SQL server to accept remote connection yet. To enable, you can see my post at Enable remote connection to SQL Server 2005 Express.
December 4th, 2007 at 3:48 pm
great stuff, specially about enabling remote connections in sql server 2005, i was struggling with that.
January 10th, 2008 at 2:22 am
String connectionUrl = “jdbc:sqlserver://localhost:1433;� +
“databaseName=visual_ftlhn;user=jboni0;password=exegis19740427″;
how would i conert this to mysql database :”jdbc:mysql://localhost:1527;” data base name ia =”vist” username is =”kumar” password=”kumar”
plz get me the syntax for it 2 represnt
January 12th, 2008 at 8:12 pm
The program compile fine but when I run it I get this message:
SQL Exception: com.microsoft.sqlserver.jdbc.SQLServerException: The TDS prelogin response is incomplete. The target server must be SQL Server 2000 or later.
BUILD SUCCESSFUL (total time: 1 second)
Any idea
Thanks
January 12th, 2008 at 8:43 pm
I forgot to mention that I have sql server 7.0 installed on OS Windows 2000.
January 14th, 2008 at 9:29 pm
To Adam,
The error message tells that you have used earlier version of SQL Server which is not support. The target server must be SQL Server 2000 or later.
You can visit this thread for more information.
http://forum.java.sun.com/thread.jspa?threadID=725228&tstart=0
To kumar,
For given attributes in your comment, the connection string to MySQL would be like
String connectionUrl = “jdbc:mysql://localhost:1527/vist?” +
“user=kumar&password=kumar”;
Or you can visit my post about MySQL Connection at
http://www.linglom.com/2007/12/05/accessing-mysql-on-netbeans-using-jdbc-part-i-create-a-connection/
March 17th, 2008 at 8:42 pm
[...] Part II : Perform SQL Operations This part show how to perform some basic operations from NetBeans with SQL Server. For instance, send querys as SELECT, INSERT, UPDATE to the database. [...]
April 10th, 2008 at 12:46 pm
was a very good one and easy to learn .Helped me a lot. thanks a lot
June 19th, 2008 at 2:52 am
thaks 4 u`r tute….
June 20th, 2008 at 10:31 pm
Thanks a lot for the comment.
June 25th, 2008 at 3:57 am
This is probably the best explanation on this topic I found online. Very helpful. Thanx.