时间:2021-07-01 10:21:17 帮助过:56人阅读
package py.db.com; import java.awt.List; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.util.ArrayList; public class DB_Select { public static void main(String[] args) { testSelect1(); } private static void testSelect1() { String url = "jdbc:mysql://localhost:3306/test"; String user = "root"; String password = "uplooking"; String sql1="select * from emp"; String sql2="select * from emp where sal > ?"; String sql3="select * from ?"; String sql4="select * from emp where ename = ?"; Connection conn = null; PreparedStatement ps = null; ResultSet rs = null; try { Class.forName("com.mysql.jdbc.Driver"); System.out.println("数据库驱动加载成功"); conn = DriverManager.getConnection(url, user, password); System.out.println("数据库连接建立成功"); ps = conn.prepareStatement(sql4); ps.setString(1, "SMITH"); rs = ps.executeQuery(); //------------------------------------------// //获取列数据 ResultSetMetaData rsmd = rs.getMetaData(); //ResultSetMetaData是ResultSet元数据的说明 int colNum = rsmd.getColumnCount(); int rowNum = 0; //该变量是为了获取我拿了多少行 java.util.List<Object[]> list = new ArrayList<Object[]>(); while (rs.next()) { rowNum++; //System.out.println(rs.getString("ename")); //获取某列的值 Object[] arrs = new Object[colNum]; for (int i = 1; i <= colNum; i++) { Object obj = rs.getObject(i); arrs[i-1] = obj; } list.add(arrs); } System.out.println("有多少行记录: "+rowNum); for (Object[] objects : list) { for (Object object : objects) { System.out.print(object + " "); } System.out.println(); } //------------------------------------------// } catch (ClassNotFoundException e) { System.out.println("数据库驱动加载失败"); e.printStackTrace(); } catch (SQLException e) { System.out.println("数据库通信失败"); e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } finally { try { rs.close(); ps.close(); conn.close(); } catch (Exception e2) { System.out.println("对象关闭失败"); } } } }
本文出自 “影魔登场” 博客,请务必保留此出处http://woodywoodpecker.blog.51cto.com/4820467/1649754
java 数据库 常规select操作
标签:java mysql select