题目:连接数据库,取出数据。
用到的类:
Connection:连接数据库
Statement:The object used for executing a static SQL statement and returning the results it produces.
ResultSet:A table of data representing a database result set, which is usually generated by executing a statement that queries the database.
package everyDay; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; import java.util.ArrayList; import java.util.List; import org.junit.Test; public class GetData { @Test public void mysqlconnection() { try { String url = "jdbc:mysql://10.255.255.148:3306/testresults"; String user = "user"; String password = "pwd"; Connection conn = DriverManager.getConnection(url, user, password); Statement stmt = conn.createStatement(); //conn.setAutoCommit(false); String sql = "select timeStamp, elapsed from cpuInfo order by timeStamp"; ResultSet rs = stmt.executeQuery(sql); //conn.commit(); //conn.setAutoCommit(true); List<String> list = new ArrayList<String>(); while (rs.next()) { list.add(rs.getString(1));//添加其中一列 } if (list != null && list.size() > 0) {// 如果list中存入了数据,转化为数组 String[] arr = new String[list.size()];// 创建一个和list长度一样的数组 for (int i = 0; i < list.size(); i++) { arr[i] = list.get(i);// 数组赋值。 } // 输出数组 for (int i = 0; i < arr.length; i++) { System.out.println(arr[i]); } } } catch (Exception e) { // TODO: handle exception } } }