· 8 years ago · May 31, 2018, 06:34 AM
1import org.telegram.telegrambots.api.methods.send.SendMessage;
2import org.telegram.telegrambots.exceptions.TelegramApiException;
3
4import java.net.MalformedURLException;
5import java.sql.*;
6import java.util.ArrayList;
7import java.util.List;
8
9public class DBusers {
10 private Connection c = null;
11
12 public DBusers(){
13 c = null;
14 String url = "jdbc:sqlite:C:\\DataBase\\SQLite\\db.sqllite";
15 try {
16 c = DriverManager.getConnection(url);
17
18 Statement stmt;
19 stmt = c.createStatement();
20 String sql = "CREATE TABLE IF NOT EXISTS USERTGram " +
21 "(ID INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL," + "ChatId BIGINT UNIQUE NOT NULL)";
22 stmt.execute(sql);
23 //stmt.exe(sql);
24 stmt.close();
25 } catch (Exception e) {
26 System.err.println(e.getMessage());
27 e.printStackTrace();
28 return;
29 }
30 System.out.println("Opened database successfully");
31 }
32
33 public List<Long> getAllNames() throws SQLException {
34 List<Long> result = new ArrayList<>();
35 Statement stmt = c.createStatement();
36 ResultSet rs = stmt.executeQuery(
37 "SELECT ChatId FROM USERTGram" );
38 while (rs.next()) {
39 Long name = rs.getLong("ChatId");
40 result.add(name);
41 }
42 rs.close();
43 stmt.close();
44 return result;
45 }
46
47 public void insert(Long ChatId) throws SQLException {
48 Statement stmt;
49 stmt = c.createStatement();
50 String sql = "INSERT INTO USERTGram (ChatId) " + "VALUES (%d);";
51 stmt.execute(String.format(sql, ChatId));
52 stmt.close();
53 }
54
55 public void delete(Long ChatId) throws SQLException {
56 Statement stmt;
57 stmt = c.createStatement();
58 String sql = "DELETE FROM USERTGram WHERE ChatId=" + "(%d);";
59 stmt.execute(String.format(sql, ChatId));
60 stmt.close();
61 }
62
63 public void getAllNamesFromDB() throws SQLException, MalformedURLException, TelegramApiException {
64 Response msg=new Response();
65 DBusers dBusers = new DBusers();
66 for (int i = 0; i < dBusers.getAllNames().size(); i++) {
67 SendMessage sendMessage=new SendMessage().setChatId(dBusers.getAllNames().get(i));
68 msg.sendMessage(sendMessage.setText(msg.getResponse()));
69 }
70 }
71}