-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathExecSQL.java
More file actions
93 lines (85 loc) · 2.34 KB
/
Copy pathExecSQL.java
File metadata and controls
93 lines (85 loc) · 2.34 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
package ch24;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;
import java.sql.SQLException;
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
/**
Executes all SQL statements from a file or the console.
*/
public class ExecSQL
{
public static void main(String[] args)
throws SQLException, IOException, ClassNotFoundException
{
if (args.length == 0)
{
System.out.println(
"Usage: java -classpath driver_class_path"
+ File.pathSeparator
+ ". ExecSQL propertiesFile [SQLcommandFile]");
return;
}
SimpleDataSource.init(args[0]);
Scanner in;
if (args.length > 1)
{
in = new Scanner(new File(args[1]));
}
else
{
in = new Scanner(System.in);
}
try (Connection conn = SimpleDataSource.getConnection();
Statement stat = conn.createStatement())
{
while (in.hasNextLine())
{
String line = in.nextLine();
try
{
boolean hasResultSet = stat.execute(line);
if (hasResultSet)
{
try (ResultSet result = stat.getResultSet())
{
showResultSet(result);
}
}
}
catch (SQLException ex)
{
System.out.println(ex);
}
}
}
}
/**
Prints a result set.
@param result the result set
*/
public static void showResultSet(ResultSet result)
throws SQLException
{
ResultSetMetaData metaData = result.getMetaData();
int columnCount = metaData.getColumnCount();
for (int i = 1; i <= columnCount; i++)
{
if (i > 1) { System.out.print(", "); }
System.out.print(metaData.getColumnLabel(i));
}
System.out.println();
while (result.next())
{
for (int i = 1; i <= columnCount; i++)
{
if (i > 1) { System.out.print(", "); }
System.out.print(result.getString(i));
}
System.out.println();
}
}
}