-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathJSON.java
More file actions
67 lines (63 loc) · 2.46 KB
/
Copy pathJSON.java
File metadata and controls
67 lines (63 loc) · 2.46 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
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import java.sql.*;
/**
* @author theDogKnight
* @date : 2018.06.30 09:26
* @email: 1123706238@qq.com
*/
public class DataBaseOperation {
private static final String DRIVER_NAME = "com.mysql.jdbc.Driver";
private static final String URL_FORMER = "jdbc:mysql://localhost:3306/";
public static Connection connection = null;
public static Statement statement = null;
/**
* 连接数据库
* @param URL_LATTER 数据库的名称
* @param USER_NAME 用户名
* @param PASSWORD 用户密码
*/
public static void setConnection(String URL_LATTER,String USER_NAME,String PASSWORD){
String url = URL_FORMER + URL_LATTER;
try {
Class.forName(DRIVER_NAME);
//获取数据库连接
System.out.println("Connecting to a selected database...");
connection = DriverManager.getConnection(url,USER_NAME,PASSWORD);
System.out.println("Connected database successfully");
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
}
/**
* 查找表内字段
*
* @param tableName 要操作的表的名称
* @param valueName 要操作的字段的名称
*/
public static JSONArray searchTable(String tableName, String valueName,int limit) throws SQLException {
JSONArray array = new JSONArray();
try {
statement = connection.createStatement();
String sql = "SELECT " + valueName + " FROM " + tableName;
System.out.println("reading database...");
ResultSet resultSet = statement.executeQuery(sql);
ResultSetMetaData resultSetMetaData = resultSet.getMetaData();
int columnCount = resultSetMetaData.getColumnCount();
while (resultSet.next()) {
JSONObject jsonObject = new JSONObject();
for (int i = 1; i <= columnCount; i++) {
String columnName = resultSetMetaData.getColumnLabel(i);
String word_value = resultSet.getString(columnName);
jsonObject.put(columnName, word_value);
}
array.add(jsonObject);
System.out.println("read database successfully");
}
}catch (SQLException e) {
e.printStackTrace();
}
return array;
}