Advertisement
Guest User

Untitled

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