Advertisement
Guest User

Untitled

a guest
Nov 29th, 2016
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.62 KB | None | 0 0
  1. import com.mysql.jdbc.Connection;
  2. import com.mysql.jdbc.Statement;
  3. import java.sql.DriverManager;
  4. import java.sql.ResultSet;
  5. import java.sql.SQLException;
  6. import java.util.logging.Level;
  7. import java.util.logging.Logger;
  8.  
  9.  
  10.  
  11. public class DBConnection {
  12.  
  13. Connection connection;
  14. Statement statement;
  15. //1. url
  16. String url = "jdbc:mysql://127.0.0.1:3306/world?user=root&password=root";
  17.  
  18. public DBConnection(){
  19. try {
  20. //2. to connect to DB
  21. connection =(Connection) DriverManager.getConnection(url);
  22. //3. create statement
  23. statement = (Statement) connection.createStatement();
  24.  
  25. } catch (SQLException ex) {
  26. System.out.println(ex.getMessage());
  27. System.out.println("Kopplingen till DB är felaktig");
  28. }
  29. }
  30. public void searchForCity(String name)
  31. {
  32. try {
  33. //4. execute Query
  34. ResultSet result = statement.executeQuery("SELECT name, population FROM city WHERE Name = '" + name + "'");
  35.  
  36. //5. while om man behöver fler satser, ingen while om vi inte har fler satser
  37. while(result.next()){
  38. System.out.println("The city " + result.getString(1) + " is in the DB and the population is: " + result.getInt(2));
  39.  
  40. //Alternativ sätt att skriva nedan
  41. //System.out.println("The city" + result.getString("Name") + "is in the DB and the population is" + result.getInt("Population"));
  42. }
  43. } catch (SQLException ex) {
  44.  
  45. }
  46. }
  47. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement