-
Notifications
You must be signed in to change notification settings - Fork 0
/
JDBC.java
362 lines (311 loc) · 14.6 KB
/
JDBC.java
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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
import java.util.*;
import java.awt.BorderLayout;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.*;
import java.sql.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Vector;
import java.util.regex.*;
import java.util.regex.*;
public class JDBC extends JFrame {
private JTextField queryTextField;
private JTextArea resultTextArea;
public JDBC() {
setTitle("SQL Query Validator");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Create a panel for the input query
JPanel queryPanel = new JPanel();
queryTextField = new JTextField(30);
queryPanel.add(queryTextField);
// Create a button to validate and optimize the query
JButton validateButton = new JButton("Validate");
queryPanel.add(validateButton);
// Create buttons for additional functionality
JButton clearButton = new JButton("Clear");
JButton exitButton = new JButton("Exit");
// Create a text area to display the results
resultTextArea = new JTextArea(30, 30);
resultTextArea.setEditable(false);
// Create a panel for additional buttons
JPanel buttonPanel = new JPanel();
buttonPanel.add(clearButton);
buttonPanel.add(exitButton);
// Add components to the frame
add(queryPanel, BorderLayout.NORTH);
add(resultTextArea, BorderLayout.CENTER);
add(buttonPanel, BorderLayout.SOUTH);
// Add action listener to the validate and optimize button
validateButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String originalQuery = queryTextField.getText();
String optimizedQuery = optimizeSQLQuery(originalQuery);
boolean isValid = validateSQLQuery(optimizedQuery);
if (isValid) {
// Count the number of Joins, Subqueries, Aggregate Functions, and Conditions
int numJoins = countJoins(optimizedQuery);
int numSubqueries = countSubqueries(optimizedQuery);
int numAggregateFunctions = countAggregateFunctions(optimizedQuery);
int numConditions = countConditions(optimizedQuery);
//analyzeTokens(optimizedQuery);
// Check if the query is complex
boolean isComplex = numJoins > 2 || numSubqueries > 2 || numAggregateFunctions >= 2 || numConditions > 2;
// Display the validation result, optimized query, and complexity status in the text area
resultTextArea.setText("Original Query:\n" + originalQuery + "\n\n");
//resultTextArea.append("Optimized Query:\n" + optimizedQuery + "\n\n");
resultTextArea.append("Query is valid.\n\n");
analyzeTokens(optimizedQuery);
resultTextArea.append("\nNumber of Joins: " + numJoins + "\n");
resultTextArea.append("Number of Subqueries: " + numSubqueries + "\n");
resultTextArea.append("Number of Aggregate Functions: " + numAggregateFunctions + "\n");
resultTextArea.append("Number of Conditions: " + numConditions + "\n\n");
resultTextArea.append("Complex Query: " + (isComplex ? "Yes, it's a complex query" : "No, it's not a complex query"));
//analyzeTokens(optimizedQuery);
// Show a dialog with the query result as a table
String queryResult = executeQuery(optimizedQuery);
displayQueryResultTable(queryResult);
} else {
resultTextArea.setText("Original Query:\n" + originalQuery + "\n\n");
resultTextArea.append("Query is invalid: " + getSQLErrorMessage() + "\n");
}
}
});
// Add action listener to the clear button
clearButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
queryTextField.setText("");
resultTextArea.setText("");
}
});
// Add action listener to the exit button
exitButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
// Set the frame to full screen
GraphicsDevice gd = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice();
if (gd.isFullScreenSupported()) {
gd.setFullScreenWindow(this);
} else {
setSize(800, 600); // Set a default size if full screen is not supported
}
}
private String sqlErrorMessage = "";
// Helper method to set SQL error message
private void setSQLErrorMessage(String message) {
sqlErrorMessage = message;
}
// Helper method to get SQL error message
private String getSQLErrorMessage() {
return sqlErrorMessage;
}
// Helper method to optimize SQL query (simplified example)
private static String optimizeSQLQuery(String sqlQuery) {
// Check if the query is a SELECT statement with "*"
if (sqlQuery.trim().toUpperCase().startsWith("SELECT * FROM")) {
// Replace "*" with the column names you want to retrieve
return sqlQuery.replace("*", "column1, column2, column3");
}
return sqlQuery;
}
private void analyzeTokens(String sqlQuery) {
java.util.List<String> keywords = java.util.Arrays.asList(
"SELECT", "FROM", "WHERE", "JOIN", "INNER JOIN", "LEFT JOIN", "RIGHT JOIN", "FULL JOIN", "GROUP BY",
"ORDER BY", "HAVING", "UNION", "INSERT", "UPDATE", "DELETE", "CREATE", "DROP", "ALTER", "DISTINCT", "AS"
);
// Add more if needed
java.util.List<String> literals = new java.util.ArrayList<>();
java.util.List<String> operators = java.util.Arrays.asList("=", ">", "<", ">=", "<=", "<>", "+", "-", "*", "/"); // Add more as needed
// Pattern for identifying literals (values enclosed in single quotes)
Pattern literalPattern = Pattern.compile("'(.*?)'");
// Split the query into tokens and analyze each token
String[] tokens = sqlQuery.split("\\s+");
for (String token : tokens) {
// Check if the token is a keyword
if (keywords.contains(token.toUpperCase())) {
resultTextArea.append("Keyword: " + token + "\n");
}
// Check if the token is a literal
else if (literalPattern.matcher(token).matches()) {
literals.add(token);
resultTextArea.append("Literal: " + token + "\n");
}
// Check if the token is an operator
else if (operators.contains(token)) {
resultTextArea.append("Operator: " + token + "\n");
}
// Check if the token is an identifier
else {
resultTextArea.append("Identifier: " + token + "\n");
}
}
}
// Helper method to validate SQL query and store the results
private boolean validateSQLQuery(String sqlQuery) {
String jdbcUrl = "jdbc:mysql://localhost:3306/db2";
String jdbcUser = "";
String jdbcPassword = "";
boolean isComplex = false; // Define the variable isComplex
try (Connection connection = DriverManager.getConnection(jdbcUrl, jdbcUser, jdbcPassword)) {
try (Statement statement = connection.createStatement()) {
statement.execute(sqlQuery);
// Store the validation results in the database
String validationDetails = "Original Query:\n" + sqlQuery + "\n\n" +
"Query is valid.\n\n" +
"Number of Joins: " + countJoins(sqlQuery) + "\n" +
"Number of Subqueries: " + countSubqueries(sqlQuery) + "\n" +
"Number of Aggregate Functions: " + countAggregateFunctions(sqlQuery) + "\n" +
"Number of Conditions: " + countConditions(sqlQuery) + "\n\n" +
"Complex Query: " + (isComplex ? "Yes, it's a complex query" : "No, it's not a complex query");
// Store the validation details in the database table 'query_validation_details'
String insertValidationDetails = "INSERT INTO query_validation_details (validation_details) VALUES (?)";
try (PreparedStatement preparedStatement = connection.prepareStatement(insertValidationDetails)) {
preparedStatement.setString(1, validationDetails);
preparedStatement.executeUpdate();
}
return true; // Query is valid
}
} catch (SQLException e) {
setSQLErrorMessage(e.getMessage()); // Set SQL error message
return false; // Query is invalid
}
}
// Helper method to execute the SQL query and return the result as a string
private String executeQuery(String sqlQuery) {
String jdbcUrl = "jdbc:mysql://localhost:3306/db2";
String jdbcUser = "";
String jdbcPassword = "";
try (Connection connection = DriverManager.getConnection(jdbcUrl, jdbcUser, jdbcPassword)) {
try (Statement statement = connection.createStatement()) {
// Execute the query
boolean hasResultSet = statement.execute(sqlQuery);
// If the query returns a result set, process and return it as a string
if (hasResultSet) {
StringBuilder resultBuilder = new StringBuilder();
ResultSet resultSet = statement.getResultSet();
ResultSetMetaData metaData = resultSet.getMetaData();
int columnCount = metaData.getColumnCount();
// Append column names
for (int i = 1; i <= columnCount; i++) {
resultBuilder.append(metaData.getColumnName(i));
if (i < columnCount) {
resultBuilder.append("\t");
}
}
resultBuilder.append("\n");
// Append query results
while (resultSet.next()) {
for (int i = 1; i <= columnCount; i++) {
resultBuilder.append(resultSet.getString(i));
if (i < columnCount) {
resultBuilder.append("\t");
}
}
resultBuilder.append("\n");
}
return resultBuilder.toString();
} else {
// The query didn't return a result set (e.g., an INSERT, UPDATE, DELETE statement)
return "Query executed successfully.";
}
}
} catch (SQLException e) {
setSQLErrorMessage(e.getMessage()); // Set SQL error message
return "Error executing the query: " + e.getMessage();
}
}
// Helper method to count Joins
private static int countJoins(String sqlQuery) {
Pattern joinPattern = Pattern.compile("\\bJOIN\\b", Pattern.CASE_INSENSITIVE);
Matcher matcher = joinPattern.matcher(sqlQuery);
int count = 0;
while (matcher.find()) {
count++;
}
return count;
}
// Helper method to count Subqueries
private static int countSubqueries(String sqlQuery) {
Pattern subqueryPattern = Pattern.compile("\\bSELEC\\b", Pattern.CASE_INSENSITIVE);
Matcher matcher = subqueryPattern.matcher(sqlQuery);
int count = 0;
while (matcher.find()) {
count++;
}
return count;
}
// Helper method to count Aggregate Functions
private static int countAggregateFunctions(String sqlQuery) {
// You can add patterns for specific aggregate functions (e.g., COUNT, SUM, AVG, etc.) here
Pattern aggregatePattern = Pattern.compile("\\bCOUNT\\b|\\bSUM\\b|\\bAVG\\b|\\\\bMIN\\\\b|\\\\bMAX\\\\b", Pattern.CASE_INSENSITIVE);
Matcher matcher = aggregatePattern.matcher(sqlQuery);
int count = 0;
while (matcher.find()) {
count++;
}
return count;
}
// Helper method to count Conditions (e.g., WHERE clauses)
private static int countConditions(String sqlQuery) {
Pattern conditionPattern = Pattern.compile("\\bWHERE\\b", Pattern.CASE_INSENSITIVE);
Matcher matcher = conditionPattern.matcher(sqlQuery);
int count = 0;
while (matcher.find()) {
count++;
}
return count;
}
// Helper method to display query result as a table in a JOptionPane
private void displayQueryResultTable(String queryResult) {
String[] lines = queryResult.split("\n");
int rowCount = lines.length;
int columnCount = lines[0].split("\t").length;
// Prepare data for the table model
String[] columnNames = new String[columnCount];
Object[][] data = new Object[rowCount - 1][columnCount]; // Subtract 1 for the header row
// Parse the column names
columnNames = lines[0].split("\t");
// Parse the data rows
for (int i = 1; i < rowCount; i++) {
String[] values = lines[i].split("\t");
for (int j = 0; j < columnCount; j++) {
data[i - 1][j] = values[j];
}
}
// Create a table model and table
DefaultTableModel tableModel = new DefaultTableModel(data, columnNames);
JTable resultTable = new JTable(tableModel);
// Show the table in a scroll pane
JScrollPane scrollPane = new JScrollPane(resultTable);
scrollPane.setPreferredSize(new Dimension(600, 400));
// Show the scroll pane in a JOptionPane
JOptionPane.showMessageDialog(this, scrollPane, "Query Result", JOptionPane.INFORMATION_MESSAGE);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
new JDBC().setVisible(true);
});
}
}