package jdbc;
import java.sql.*;
public class JdbcDemo06 {
public static void main(String[] args) {
Statement stmt=null;
Connection conn=null;
ResultSet rs=null;
try{
//1、注册驱动
Class.forName("com.mysql.cj.jdbc.Driver");
//2、获取Connection对象
conn= DriverManager.getConnection("jdbc:mysql://localhost:3306/db1","root","lpl5201314");
//3、定义sql
String sql="select * from account";
//4、获取执行sql的对象 Statement
stmt=conn.createStatement();
//5、执行sql
rs=stmt.executeQuery(sql);//影响的函数
//6、处理结果
//让游标向下移动一行
rs.next();
//获取数据
int id=rs.getInt(1);
String name=rs.getString("name");
double balance=rs.getDouble(3);
System.out.println(id+"---"+name+"---"+balance);
}catch (ClassNotFoundException | SQLException e){
e.printStackTrace();
} //7、释放资源
//避免空指针异常
if(rs !=null)
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
if(stmt !=null)
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
if(conn !=null)
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
无法判断是否最后一行,进行改进
package jdbc;
import java.sql.*;
public class JdbcDemo07 {
public static void main(String[] args) {
Statement stmt=null;
Connection conn=null;
ResultSet rs=null;
try{
//1、注册驱动
Class.forName("com.mysql.cj.jdbc.Driver");
//2、获取Connection对象
conn= DriverManager.getConnection("jdbc:mysql://localhost:3306/db1","root","lpl5201314");
//3、定义sql
String sql="select * from account";
//4、获取执行sql的对象 Statement
stmt=conn.createStatement();
//5、执行sql
rs=stmt.executeQuery(sql);//影响的函数
//6、处理结果
//让游标向下移动一行
while(rs.next()){
//判断是否为最后一行末尾
//获取数据
int id=rs.getInt(1);
String name=rs.getString("name");
double balance=rs.getDouble(3);
System.out.println(id+"---"+name+"---"+balance);
}
}catch (ClassNotFoundException | SQLException e){
e.printStackTrace();
} //7、释放资源
//避免空指针异常
if(rs !=null)
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
if(stmt !=null)
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
if(conn !=null)
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}