Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.sql.Connection;
- import java.sql.DriverManager;
- import java.sql.ResultSet;
- import java.sql.SQLException;
- import java.sql.Statement;
- import java.util.LinkedList;
- import java.util.List;
- public class DBTest {
- public List<Person> testIt() throws SQLException {
- Connection con = null;
- // Verbindung aufbauen
- try {
- // jdbc:mysql://localhost/reischerTestPersons variert, je nachdem wie eure db heißt
- con = DriverManager.getConnection("jdbc:mysql://localhost/reischerTestPersons", "root","");
- } catch (SQLException e) {
- // TODO this got caught right here
- System.out.println("SQLException right here");
- e.printStackTrace();
- }
- // Statement definieren und abschicken
- Statement stmt = con.createStatement();
- ResultSet rs = stmt
- .executeQuery("SELECT persno, fname, lname FROM person");
- List<Person> persons = new LinkedList<Person>();
- // Ergebnis durchiterieren
- while (rs.next()) {
- Person p = new Person();
- p.setPersno(rs.getInt("persno"));
- p.setFname(rs.getString("fname"));
- p.setLname(rs.getString("lname"));
- persons.add(p);
- }
- //close the mySQL connection and print persons;
- con.close();
- persons.forEach((Person p) -> System.out.println(p.toString()));
- return persons;
- }
- private class Person {
- public int persno;
- public String fname;
- public String lname;
- public void setPersno(int no) {
- this.persno = no;
- }
- public void setFname(String n) {
- this.fname = n;
- }
- public void setLname(String s) {
- this.lname = s;
- }
- @Override
- public String toString() {
- return "lname: "+ lname + " fname: " + fname + " persno: " + persno;
- }
- }
- public static void main(String[] args) {
- DBTest test = new DBTest();
- try {
- List<Person> personList = test.testIt();
- } catch (SQLException e) {
- e.printStackTrace();
- System.out.println("died in main()");
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement