Skip to content

Instantly share code, notes, and snippets.

@mnl
Last active December 14, 2018 09:37
Show Gist options
  • Save mnl/b8dae72f191d63211ba980450a4f55bc to your computer and use it in GitHub Desktop.
Save mnl/b8dae72f191d63211ba980450a4f55bc to your computer and use it in GitHub Desktop.
java,sql
/**
*
*/
package dbTest;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
/**
* @author mn
*
*/
public class DbFtg1 {
static final String JDBC_DRIVER = "com.mysql.cj.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://java.bx.nimell.se:33306/javadb";
// Database credentials
static final String USER = "coffee";
static final String PASS = "hunter12";
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Connection conn = null;
Statement stmt = null;
try {
// Register JDBC driver
Class.forName(JDBC_DRIVER);
// Open a connection
System.out.println("Connecting to database...");
conn = DriverManager.getConnection(DB_URL, USER, PASS);
stmt = conn.createStatement();
String sql = "SELECT id, first, last, salary FROM Employees";
ResultSet result = stmt.executeQuery(sql);
// Show result
while (result.next()) {
// Retrieve by column name
int id = result.getInt("id");
int age = result.getInt("salary");
String first = result.getString("first");
String last = result.getString("last");
// Display values
System.out.print("ID: " + id);
System.out.print("\t Pay: " + age);
System.out.print("\tFirst: " + first);
System.out.println("\tLast: " + last);
}
// Clean-up
result.close();
stmt.close();
conn.close();
} catch (Exception e) {
System.out.println("Something went wrong");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment