Thursday, July 7, 2011

get last inserted id from database table in Java, .NET , PHP

When we tried to retrieve a new record ID immediately after insertion,We did face bit trouble in getting that.

Different languages have different syntax/process of doing this.

Here is, How did I manage to get this done, in required projects:
For Java & PHP , we are using MySql dtabase, while in .NET we have used SQL server.

Java



//DBHelper , written for Database handling
DBHelper dbHelper = new DBHelper();
       Connection con = null;
       
String querySave = "";

       querySave = "INSERT INTO `DATABASE_NAME`.`TABLE_NAME` (`FIELD`) VALUES ( '"
               + VALUE_TO_BE_INSERTED + "');";
       Statement stmt = null;
       ResultSet rs = null;
       try {
//con is connection to database
           this.con = dbHelper.openDB(); //Here dbHelper is an instance of class,
           stmt = con.createStatement();
           int insertedRow = stmt.executeUpdate(querySave,
                   Statement.RETURN_GENERATED_KEYS);
           rs = stmt.getGeneratedKeys();
           int key = 0;
           if (rs.next()) {
               // Retrieve the auto generated key(s).
               key = rs.getInt(1);
               System.out.println("last inserted key is : " + key);

           }
catch (SQLException e) {
           e.printStackTrace();
       }
finally {
           dbHelper.closeDB();
           if (stmt != null) {
               stmt.close();
               stmt = null;
           }
           if (rs != null) {
               rs = null;
           }
           if (this.con != null) {
               this.con = null;
           }
       }


.NET



//dbManager - an object of one of the class from DATA Access Layer
  string sql = "INSERT INTO tgc_user_profile(firstName,emailId, password) VALUES(@firstName,@emailId,@password);" + "SELECT uid FROM tgc_user_profile WHERE uid = @@IDENTITY";

           try
           {
               dbManager.OpenConnection();

               dbManager.AddParameter("@firstName", name);
               dbManager.AddParameter("@emailId", email);
               dbManager.AddParameter("@password", password);

                ID = (int)dbManager.ExecuteScalar(sql, CommandType.Text);
               
       
           }

           catch (Exception ex)
           {
             
           }

           finally
           {
               dbManager.CloseConnection();
           }


PHP




$fName=mysql_real_escape_string($fName);
$email=mysql_real_escape_string($email);
$password=mysql_real_escape_string($password);
//mysql_real_escape_string to avoid sql injection attacks ,as we are using dynamic SQL query
$query_save = "INSERT INTO tgc_user_profile(firstName,emailId, password)
               VALUES ('".$fName."', '" .$email."', '" .$password ."')";
                             
             $_result = mysql_query($query_save);
            $ID = mysql_insert_id();


Hope this helps :)

Your valuable comments are appreciated !

2 comments: