Advertisement
VladimirSimic

2

Mar 16th, 2018
100
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.30 KB | None | 0 0
  1. dbutil vesti
  2.  
  3. /*
  4.  * To change this license header, choose License Headers in Project Properties.
  5.  * To change this template file, choose Tools | Templates
  6.  * and open the template in the editor.
  7.  */
  8. package zadatak1;
  9.  
  10. import java.sql.DriverManager;
  11. import java.sql.PreparedStatement;
  12. import java.sql.ResultSet;
  13. import java.sql.SQLException;
  14. import java.sql.Statement;
  15. import java.util.ArrayList;
  16. import java.util.List;
  17.  
  18. /**
  19.  *
  20.  * @author ladmin
  21.  */
  22. public class DBUtil {
  23.  
  24.     private static java.sql.Connection con = null;
  25.     private static String url = "jdbc:mysql://localhost/vesti";
  26.     private static String user = "root";
  27.     private static String password = "";
  28.  
  29.     public static void openConnection() throws SQLException {
  30.         con = DriverManager.getConnection(url, user, password);
  31.     }
  32.  
  33.     public static void closeConnection() throws SQLException {
  34.         con.close();
  35.     }
  36.  
  37.     public static void createTable() throws SQLException {
  38.         openConnection();
  39.         Statement sql = con.createStatement();
  40.         sql.execute("create table if not exists vest( id int auto_increment, "
  41.                 + "naslov varchar(400), link varchar(400),  "
  42.                 + "slika varchar(300),  primary key(id))");
  43.  
  44.         closeConnection();
  45.     }
  46.  
  47.     public static void addVest(VestMetropolitan vest) throws SQLException {
  48.         openConnection();
  49.         PreparedStatement sql = con.prepareStatement("INSERT INTO `vest`"
  50.                 + "(`naslov`, `link`, `slika`) VALUES (?,?,?)");
  51.         sql.setString(2, vest.getNaslov());
  52.         sql.setString(3, vest.getLink());
  53.         sql.setString(4, vest.getSlika());
  54.  
  55.         sql.execute();
  56.  
  57.         closeConnection();
  58.     }
  59.  
  60.     public static List<VestMetropolitan> selectVesti() throws SQLException {
  61.         openConnection();
  62.         Statement sql = con.createStatement();
  63.         ResultSet rs = sql.executeQuery("select * from vest order by naslov asc");
  64.         List<VestMetropolitan> vesti = new ArrayList<>();
  65.  
  66.         while (rs.next()) {
  67.             String naslov = rs.getString(1);
  68.             String link = rs.getString(2);
  69.             String slika = rs.getString(3);
  70.             vesti.add(new VestMetropolitan(naslov, slika, link));
  71.         }
  72.  
  73.         closeConnection();
  74.         return vesti;
  75.  
  76.     }
  77. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement