Blog

How to get the number of columns in a ResultSet in Java

In Java it is possible to retrieve the number of columns of a ResultSet dinamically, thanks to the ResultSetMetaData class. Here’s an example:

   
// Here you get the conn object. E.g.:
// Connection conn = DriverManager.getConnection(...);

Statement st = conn.createStatement();
ResultSet rs = st.executeQuery("SELECT * FROM your_table");
ResultSetMetaData rsmd = rs.getMetaData();
int numCols = rsmd.getColumnCount();
System.out.println("Number of columns in your_table: " + numCols);

The previous code retrieves and displays the number of columns of your_table.

Read more...

Capturing groups using regular expressions (RegEx) in JavaScript

There are whole books about regular expressions so this post shouldn’t be intended as an exhaustive resource on the subject. It just shows how to extract a substring from a string using regular expressions in JavaScript so it must be considered just a tip not a tutorial on RegExp. Look at the following example:

    
var str = "https://www.alessandrolacava.com/?code=ALE69";
var regex = /code=(w+)&?/;
var results = regex.exec(str);
if(!results){
  alert("no match");
}
else{
  // first group
  alert(results[1]);
}

The previous code extracts the string that follows the code= part of str. That string is captured in the first group. of the RegExp, that’s why I use results[1] to display it. When you utilise groups–through the use of parenthesis ()–you can refer to them using indices, starting from 1. Indeed, at the index 0 you find the whole match. In the previous example, results[0] is equal to code=ALE69

Read more...

How to compute the timestamp in JavaScript

Many sources use the term timestamp to refer specifically to Unix time, the number of seconds since 00:00:00 UTC on January 1, 1970. In JavaScript you can use the built-in object Date to compute this timestamp. Here follows an example:

 
var ts = Date.UTC('2007', '09', '28') / 1000;
alert(ts);

The previous code displays an alert with the number of seconds between 00:00:00 UTC on January 1, 1970 and 00:00:00 UTC on October 28, 2007.

Read more...