import java.sql.*; public class Main { public static void main(String[] args) { String driver = "com.mysql.jdbc.Driver"; String url = "jdbc:mysql://localhost:3306/test"; String username = "root"; String password = "root"; String sql = "select * from user "; Connection conn = null; PreparedStatement pre=null; ResultSet res=null; try { Class.forName(driver); //classLoader,加载对应驱动 conn = (Connection)DriverManager.getConnection(url, username, password); pre=conn.prepareStatement(sql); res=pre.executeQuery(); int col = res.getMetaData().getColumnCount(); while (res.next()){ for (int i = 1; i <= col; i++) { System.out.print(res.getString(i) + "\t"); } //查完一行换行 System.out.println(); } System.out.println("查完了"); res.close(); pre.close(); conn.close(); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } } }
结果是:
0 admin 123 1 admin 123 查完了