import java.sql.Connection;
import java.sql.Date;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Calendar;
import java.text.ParseException;
import java.text.SimpleDateFormat;
public class Connect
{
public static void main(String[] args)
{
Connection connection = null;
String url = "jdbc:mysql://localhost:8889/charthits";
String user = "root";
String password = "root";
// multiple date formats
String[] formatStrings = { "d.M.y", "d/M/y", "d-M-y","dMyyyy","ddMMyyyy","ddMMyy","dMy" };
java.util.Date d = null;
Calendar cal = Calendar.getInstance();
if (args.length > 0) {
// check if provided date is valid
d = isValidDate(args[0], formatStrings);
if (d == null) {
// date is invalid!
System.out.println("InvalidDate");
System.exit(1);
}
cal.setTime(d);
}
else {
// args is empty
System.out.println("InvalidDate");
System.exit(1);
}
try {
connection = DriverManager.getConnection(url, user, password);
Statement stmt = null;
String query = "SELECT birthday,filename,egg FROM midiFiles WHERE birthday <= '" + cal.get(Calendar.YEAR)
+ "-" + (cal.get(Calendar.MONTH) + 1) + "-" + cal.get(Calendar.DATE) + "' ORDER BY birthday DESC";
// System.out.println(cal.get(Calendar.YEAR)
// + "-" + (cal.get(Calendar.MONTH) + 1) + "-" + cal.get(Calendar.DATE));
try {
stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery(query);
if (rs.next()) {
do {
Date birthday = rs.getDate("birthday");
String filename = rs.getString("filename");
boolean egg = rs.getBoolean("egg");
if (egg) {
if (d.compareTo(birthday) == 0) {
System.out.println(filename);
break;
}
}
else {
System.out.println(filename);
break;
}
} while (rs.next());
if (rs.isAfterLast()) {
System.out.println("EmptyResult");
}
}
else {
// result is empty
System.out.println("EmptyResult");
}
}
catch (SQLException e) {
}
finally {
if (stmt != null) {
stmt.close();
}
}
connection.close();
}
catch (SQLException ex) {
}
}
private static java.util.Date isValidDate(String dateString, String[] formatStrings)
{
java.util.Date d = null;
if (dateString == null || dateString == "")
return d;
for (String formatString : formatStrings) {
try {
SimpleDateFormat sdf = new SimpleDateFormat(formatString);
sdf.setLenient(false);
d = sdf.parse(dateString);
break;
}
catch (ParseException e) {
}
}
return d;
}
}