Life in code, apps and OS's

Archive for the ‘Java Development’ Category

Since downloading and installing Microsoft VB .net 2008 Express edition yesterday and then playing with it last night whilst at home I managed to build a simple application to connect to a MySQL database and show table records (with corrisponding data using a ‘JOIN’ statement) and I must say I throughly enjoyed it.

A couple of days ago I started playing with the JAVA JDK6 (Update 10) using NetBeans and although NetBeans comes bundled with a few sample apps even looking at the code I didn’t really understand what the JAVA source was doing however VB.net really did seem simple and I felt that I understood what the code was doing.

I now intend to start and play with VB.net, Create a few application etc.

Since developing software for the internet mainly using PHP as well as ColdFusion I have always used MySQL for a number of reasons really…

  • Supported well by the community
  • Its Opensource (Free)
  • Owned by one of the Technoligy giants (Sun Microsystems)

As I have always really used MySQL and am comfortable with it, I still intend to keep using it and most of my applications I will be building will be using MySQL as its back end. – However now Microsoft have released SQL Server 2008 Express edition which is also freely avaliable (with some limitations however) I may even use that from time to time.

So how is VB .net 2008 going to help me, what will I be using it for?? – Well to be honest I’ve never really gotten into developing System Applications and in the past have dedicated my time to developing Web Applications but everyday I see solutions that I feel would definetly work well in conjunction with certain web applications I have developed in the past for example:-

  • Bug Tracking systems – Client to add a bug directly from a user desktop.
  • Bug Tracking systems – Developers task list application.
  • Social network sites – Instant Messenger based on friends list.
  • Software Deployment suite – Download and install client (running as a service)
  • Corporate Web Applications – BackOffice tool to create, edit and ammend records.

Really the list is endless with what you can do and I intend on furthering my knowledge with this language and implement database connected applications for many of my exisiting projects.

Advertisements

This tutorial will read all rows in a MySQL database and print out the resaults.

Create a new Java source file and save it as JdbcExample3.java in the same folder where you’ve been keeping others files for this tutorial. Now copy/paste following code in it:

package com.stardeveloper.example;

import java.sql.*;

public class JdbcExample3 {

  public static void main(String args[]) {
    Connection con = null;
    Statement st = null;
    ResultSet rs = null;

    try {
      Class.forName("com.mysql.jdbc.Driver").newInstance();
      con = DriverManager.getConnection("jdbc:mysql:///examples",
        "root", "secret");

      st = con.createStatement();
      rs = st.executeQuery("SELECT user_id, first_name, last_name, " +
        "country_code FROM users");

      while(rs.next()) {
        int userId = rs.getInt(1);
        String firstName = rs.getString(2);
        String lastName = rs.getString(3);
        String countryCode = rs.getString(4);

        System.out.println(userId + ". " + lastName + ", " +
            firstName + " (" + countryCode + ")");
      }

    } catch (Exception e) {
      System.err.println("Exception: " + e.getMessage());
    } finally {
      try {
        if(rs != null)
          rs.close();
        if(st != null)
          st.close();
        if(con != null)
          con.close();
      } catch (SQLException e) {
      }
    }
  }
}

Explanation
First line is the package statement that tells the Java compiler that our JdbcExample3 class belongs to com.stardeveloper.example package.

package com.stardeveloper.example;

Next we import the required JDBC classes from java.sql package.

import java.sql.*;

Next we give a name to our class, i.e. JdbcExample3.

public class JdbcExample3 {
	...
}

Next we create a main() method for our class. This is where our JDBC code will reside.

public static void main(String args[]) {
	...
}

We create 3 variables to hold Connection, Statement and ResultSet objects for us which we’ll create later in a try/catch/finally block.

	Connection con = null;
	Statement st = null;
	ResultSet rs = null;

We then enter a try/catch/finally block. Our data access code will reside in the try block, exception notification code in the catch block and code to close the connection in the finally block.

	try {
		...
	} catch (Exception e) {
      System.err.println("Exception: " + e.getMessage());
	} finally {
		...
	}

First thing we do to display records is to obtain a connection to MySQL database and that we do that my first loading it’s JDBC (Connector/J) driver and then using DriverManager to obtain a connection to our “examples” database. You might want to change the password from “secret” to whatever is your password for ‘root’ account.

	Class.forName("com.mysql.jdbc.Driver").newInstance();
	con = DriverManager.getConnection("jdbc:mysql:///examples",
	  "root", "secret");

Once we are connected, we create a new SQL Statement object.

	st = con.createStatement();

We then execute this statement to obtain a ResultSet which contains all the records from the “users” table and we do that by executing a SELECT SQL statement.

	rs = st.executeQuery("SELECT user_id, first_name, last_name, " +
		"country_code FROM users");

We then iterate through that ResultSet to obtain values for each field of the “users” table. We then print these values on the user console.

	while(rs.next()) {
		int userId = rs.getInt(1);
		String firstName = rs.getString(2);
		String lastName = rs.getString(3);
		String countryCode = rs.getString(4);

		System.out.println(userId + ". " + lastName + ", " +
		firstName + " (" + countryCode + ")");
	}

In the finally block we close off our ResultSet, Statement and Connection objects.

	try {
		if(rs != null)
			rs.close();
		if(st != null)
			st.close();
		if(con != null)
			con.close();
	} catch (SQLException e) {}

Compiling JdbcExample3.java
To compile JdbcExample3.java, execute following command at the command prompt from the folder where JdbcExample3.java is residing:

javac -d . JdbcExample3.java
Command Prompt - Compiling JdbcExample3.java
Command Prompt – Compiling JdbcExample3.java

You should now have JdbcExample3.class file under the com/stardeveloper/example folder.

Running JdbcExample3
Before we run our Java program, make sure that MySQL server is running and that you’ve properly created and setup “examples” database and “users” table. Now to run our Java program, execute following command at the command prompt from the folder from where you compiled JdbcExample3.java:

java com.stardeveloper.example.JdbcExample3
Command Prompt - Running JdbcExample3
Command Prompt – Running JdbcExample3

Congratulations! you’ve successfully been able to display all the records from “users” tables in the MySQL “examples” database using JDBC in your Java program.

Summary
In this tutorial we learned how to display records from a table in a MySQL database using JDBC in a Java program.

In next article we will learn what is java.sql.PreparedStatement and how to make use of it.

Hi everyone, sorry I havent been posting much recently this is mainly due to me being busy at work and on other projects I am currently working on such as my new web-based MMORPG (I will post more about this soon!)

Anyway so…

I have decided to start learning to develop applications in JAVA mainly my reasons for doing so are as follows:-

  • Java is platform independant (Runs on Windows, Linux & UNIX)
  • Java is maintained by Sun Microsystems (A big player)
  • Java is NOT developed or in anyways associated with Micro$oft!!!
  • Java is free and open-source.

I will be keeping my blog updated over the next couple of weeks with tips, tricks and how-to’s so others like me can learn and hopefully start developing some really awesome applications.

For now, please go and download the following peices of software if you intend to follow my tutorials in my up-coming blog posts…

Firstly we will need to download the JDK (Java Development Kit) This is required by NetBean’s (The Opensource IDE that I will be using), The JDK will enable us to test and deploy our applications this also intergrates with NetBeans to enable faster testing etc!! I have downloaded and currently using JDK 6 (Update 10), You can download your copy from here: http://java.sun.com/javase/downloads/index.jsp – To install just run the downloaded installer and accept all defaults.

Now, NetBean’s is a multi-language development IDE from what I have seen from it so far, It really is a good peice of kit, I have downloaded version NetBeans 6.1, You can download your copy from here: http://www.netbeans.org/downloads/, I simply download the bundle named (Web & JAVA EE).

When installing Netbeans you can simply follow the installer accepting the defaults if you want to however, I decided to uncheck the Application Server installation as I do not intend to using NetBeans nor Java to develop Web based application (As I am much more fulent with PHP)… So simply just untick the following two options from the installer.

  1. GlassFish V2 URL2
  2. Apache Tomcat 6.0.16

Then continue… You’ll then have to accept the license agreement and accept the program installation directory then the software will install application and all other required file etc. – The installer will use ~300MiB to install the IDE (So just be sure you have enough room on your PC) :).

So thats all for now folks, I will continue to play around with the software and post any interesting infomation etc as my experience as a JAVA developer grows 🙂



  • How To Dyndns Ubuntu | Order Goods: […] DynDNS Client Setup on Ubuntu | Life in code, apps and OS’s – May 18, 2008  · 7 Responses to "DynDNS Client Setu
  • lizrandolph10886: Wonderful article! We are linking to this particularly great post on our website.nKeep up the great writing. Click
  • waseem Ahmad: Dear. i have a separate application server and a separate mysql database server. when i want to access the application server to login from the local