-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMyDatabase.java
More file actions
107 lines (98 loc) · 3.31 KB
/
MyDatabase.java
File metadata and controls
107 lines (98 loc) · 3.31 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
package BACKUPER;
import java.sql.*;
public class MyDatabase {
private Connection connection;
private static String fileName="backuperDatabase.db";
private final static String startClientsTable="CREATE TABLE IF NOT EXISTS clients(" +
"id INTEGER PRIMARY KEY,"+
"login TEXT,"+
"password TEXT);";
private final static String startFilesTable = "CREATE TABLE IF NOT EXISTS files (" +
"id INTEGER PRIMARY KEY,"+
"name TEXT,"+
"length INTEGER,"+
"path TEXT," +
"version INTEGER);";
public void connect(String path){
try{
String url=path+fileName;
connection= DriverManager.getConnection(url);
System.out.println("Connection established");
}
catch (SQLException e){
System.err.println("Cannot connect to a database");
}
}
public void startDatabase(int flag){
if(flag==0) {
if (connection != null) {
try {
Statement statement = connection.createStatement();
statement.execute(startClientsTable);
} catch (SQLException e) {
System.err.println("Cannot start database");
}
}
}
else if(flag==1){
if (connection != null) {
try {
Statement statement = connection.createStatement();
statement.execute(startFilesTable);
} catch (SQLException e) {
System.err.println("Cannot start database");
}
}
}
}
public ResultSet selectViaSQL(String sql){
try {
Statement statement = connection.createStatement();
return statement.executeQuery(sql);
}
catch (SQLException e){
System.err.println("Cannot find data");
return null;
}
}
public void newFile(String name,long length, String path,int version){
String sql="INSERT INTO files(name,length,path,version) VALUES(?,?,?,?)";
try{
PreparedStatement statement=connection.prepareStatement(sql);
statement.setString(1,name);
statement.setLong(2,length);
statement.setString(3,path);
statement.setInt(4,version);
statement.executeUpdate();
}
catch (SQLException e){
System.err.println(e);
}
}
public void newUser(String userName,String userPassword){
String sql="INSERT INTO clients(login,password) VALUES(?,?)";
try{
PreparedStatement statement=connection.prepareStatement(sql);
statement.setString(1,userName);
statement.setString(2,userPassword);
statement.executeUpdate();
}
catch (SQLException e){
System.out.println("New user added!: "+userName+".");
System.err.println(e);
}
}
public void closeConnection(){
if(connection!=null){
try{
connection.close();
}
catch (SQLException e){
System.err.println("Cannot close the connection");
}
finally {
connection=null;
}
}
}
}