Reputation: 9205
From the CentOS 7 terminal, I can run the java program below by typing javac /path/to/TestJDBC.java
. But the problem is that the SYSO commands in the program have no place to go when called from the terminal. How can I change the Java code below so that the SYSO commands get printed to the terminal instead? I know that I could use a FileOutputStream() and then nano the created file name, but I would like to avoid creating a bunch of unnecessary test files.
package somepackage;
//STEP 1. Import required packages
import java.sql.*;
public class TestJDBC {
// JDBC driver name and database URL
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost:3306/somedb?autoReconnect=true";
// Database credentials
static final String USER = "usrname";
static final String PASS = "pword";
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try{
//STEP 2: Register JDBC driver
Class.forName("com.mysql.jdbc.Driver");
//STEP 3: Open a connection
System.out.println("Connecting to database...");
conn = DriverManager.getConnection(DB_URL,USER,PASS);
//STEP 4: Execute a query
System.out.println("Creating statement...");
stmt = conn.createStatement();
String sql;
sql = "SELECT id, name FROM peeps";
ResultSet rs = stmt.executeQuery(sql);
//STEP 5: Extract data from result set
while(rs.next()){
//Retrieve by column name
int id = rs.getInt("id");
String name = rs.getString("name");
//Display values
System.out.print("ID: " + id);
System.out.println(", name: " + name);
}
//STEP 6: Clean-up environment
rs.close();
stmt.close();
conn.close();
}catch(SQLException se){
//Handle errors for JDBC
se.printStackTrace();
}catch(Exception e){
//Handle errors for Class.forName
e.printStackTrace();
}finally{
//finally block used to close resources
try{
if(stmt!=null)
stmt.close();
}catch(SQLException se2){
}// nothing we can do
try{
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
}//end finally try
}//end try
System.out.println("Goodbye!");
}//end main
}//end FirstExample
EDIT
I tried @Immibis's method, and the program starts to run by throws a java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
error at the line of code that says Class.forName("com.mysql.jdbc.Driver");
. I cannot really evaluate the ability of the program to print to the terminal until errors like this are resolved. How can I resolve this and similar errors in the simple code above?
Upvotes: 1
Views: 487
Reputation: 58947
javac
is the compiler. You are compiling your program, but not running it.
Since your package is somepackage
, you should have a folder somepackage
containing TestJDBC.java
. cd
to that folder, then run:
javac somepackage/TestJDBC.java
java somepackage.TestJDBC
(It is usually a good idea to make your source folders follow your package structure)
Upvotes: 1