Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import com.mysql.jdbc.Connection;
- import com.mysql.jdbc.Statement;
- import java.sql.DriverManager;
- import java.sql.ResultSet;
- import java.sql.SQLException;
- import java.util.logging.Level;
- import java.util.logging.Logger;
- public class DBConnection {
- Connection connection;
- Statement statement;
- //1. url
- String url = "jdbc:mysql://127.0.0.1:3306/world?user=root&password=root";
- public DBConnection(){
- try {
- //2. to connect to DB
- connection =(Connection) DriverManager.getConnection(url);
- //3. create statement
- statement = (Statement) connection.createStatement();
- } catch (SQLException ex) {
- System.out.println(ex.getMessage());
- System.out.println("Kopplingen till DB är felaktig");
- }
- }
- public void searchForCity(String name)
- {
- try {
- //4. execute Query
- ResultSet result = statement.executeQuery("SELECT name, population FROM city WHERE Name = '" + name + "'");
- //5. while om man behöver fler satser, ingen while om vi inte har fler satser
- while(result.next()){
- System.out.println("The city " + result.getString(1) + " is in the DB and the population is: " + result.getInt(2));
- //Alternativ sätt att skriva nedan
- //System.out.println("The city" + result.getString("Name") + "is in the DB and the population is" + result.getInt("Population"));
- }
- } catch (SQLException ex) {
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement