Here is my class:
import java.sql.Connection;
import java.sql.Statement;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
public class DisplayAuthors {
static final String JDBC_DRIVER = "com.mysql.jdbc.driver";
static final String DATABASE_URL = "jdbc:mysql://localhost/myfirstdb";
public static void main(String[] args) {
Connection connection = null;
Statement statement = null;
try {
Class.forName(JDBC_DRIVER);
connection = DriverManager.getConnection(DATABASE_URL, "root", "1234");
statement = connection.createStatement();
ResultSet resultset = statement.executeQuery("SELECT S_ID, S_NAME, AGE, CLASS FROM MYOWN");
ResultSetMetaData metaData = resultset.getMetaData();
int numberOfColumns = metaData.getColumnCount();
System.out.println("Table Content");
for(int i = 1; i<+numberOfColumns; i++)
System.out.printf("%-8s\t", metaData.getColumnName(i));
System.out.println();
ResultSet resultSet;
while (resultSet.next())
{
for (int i = 1; i<+numberOfColumns; i++)
System.out.printf("%-8s\t", resultSet.getObject(i));
System.out.println();
}
}
catch ( SQLException sqlException)
{
sqlException.printStackTrace();
System.exit(1);
}
catch ( ClassNotFoundException classNotFound)
{
classNotFound.printStackTrace();
System.exit(1);
}
finally
{
try
{
statement.close();
connection.close();
}
catch ( Exception exception )
{
exception.printStackTrace();
System.exit(1);
}
}
}
}
This runs fine in Eclipse and outputs as follows:
testing oracle-character-set-1 against <abc>
PASSED LOSSY
testing oracle-character-set-1 against <ab?c>
PASSED LOSSY
testing oracle-character-set-1 against <XY
I also tried to compile and run in CMD, but it gives the following compilation errors:
C:\My Java>javac DisplayAuthors.java
DisplayAuthors.java:43: cannot resolve symbol
symbol : method printf (java.lang.String,java.lang.String)
location: class java.io.PrintStream
System.out.printf( "%-8s\t", metaData.getColumnName( i ) );
^
DisplayAuthors.java:49: cannot resolve symbol
symbol : method printf (java.lang.String,java.lang.Object)
location: class java.io.PrintStream
System.out.printf( "%-8s\t", resultSet.getObject( i ) );
^
2 errors
How can I fix this?