MySQL & JavaFx

Connecting to database in JavaFx is very similar to connecting to database in Java. Good thing about JavaFx is that it can leverage all Java libraries. So, here in this example we are going to use java.sql.* libraries and MySQL connector(must be downloaded). Here is a simple code to connect to MySQL.


import java.sql.Connection;
import java.sql.ResultSet;
import java.lang.Class;
import java.sql.DriverManager;
import java.lang.InstantiationException;
import java.lang.IllegalAccessException;
import java.sql.SQLException;
import java.sql.PreparedStatement;

public class DBConnection
{
 var userName = "user";//username to connect to mysql
 var password = "user";//password to connect to mysql
 var driverClass = "com.mysql.jdbc.Driver";//driver class to connect to mysql
                                           //needs mysql connector jar
 var db_url = "jdbc:mysql://localhost/LOGIN";//LOGIN is the database.
 var connectionString:Connection;

 function getConnection():Connection
 {
   var conString: Connection = null;
   try
   {
      Class.forName(driverClass).newInstance();
      conString = DriverManager.getConnection(db_url, userName, password);

      if(not conString.isClosed())
      {
         println("Connection Successful");
      }
   }
   catch(ex : InstantiationException)
   {
      ex.printStackTrace();
   }
   catch(ex : IllegalAccessException)
   {
      ex.printStackTrace();
   }

   return conString;
 }

 public function login(userName:String, password:String): Boolean
 {
    connectionString = getConnection();

    var success:Boolean = false;
    var rs:ResultSet = null;

    var query:String = "SELECT FIRSTNAME FROM USERS WHERE USER_ID = ? AND PASSWORD = ?";

    try
    {
       var statement: PreparedStatement = connectionString.prepareStatement(query);

       statement.setString(1, userName);
       statement.setString(2, password);

       rs = statement.executeQuery();

       if(rs.first())
          success = true;

    }
    catch(ex : SQLException)
    {
       ex.printStackTrace();
    }

    return success;
  }
}

One thing we need to make sure is that the mysql connector jar
is downloaded and is in the class path of the project. Also the database
and the tables should exist.

Advertisements