public class Test3 {
public static void main( String[] args ){
Connection conn = null;
Statement statement = null;
try {
//1.加载驱动
Class.forName("com.mysql.jdbc.Driver");
//2.获取和数据库的连接通道
String url = "jdbc:mysql://localhost:3306/scott?characterEncoding=UTF8&autoReconnect=true&useSSL=true";
String user = "root";
String password = "123456";
conn = DriverManager.getConnection(url, user, password);
//3.获取操作数据库的方式(查询通道)
statement = conn.createStatement();
//4.查询数据
String sql = "select 'id'as 'test_id','name'from'test'";
//5.执行查询
ResultSet rs = statement.executeQuery(sql);
while (rs.next()){
//每次会获取下一条数据
//通过游标来获取指定列
// int id = rs.getInt(1);//从一开始
//通过列名来获取指定列
int id = rs.getInt("test_id");
String name = rs.getString("name");
System.out.printf("%d,%srn",name,id);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if(conn != null)
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}