标签:jdb mys close == previous com root style 数据库连接
java连接数据库
import java.sql.*;
public class Jdbc05 {
static final String URL="jdbc:mysql://localhost:3306/test";
static final String USER="root";
static final String PWD="root";
public static void main(String[] args) {
//定义sql语句
String s="select id,account,balance from bank where id=1";
Connection conn=null;
Statement statement=null;
ResultSet resultSet=null;
try {
//注册驱动
Class.forName("com.mysql.jdbc.Driver");
//获取数据库连接对象
conn= DriverManager.getConnection(URL,USER,PWD);
//获取执行sql的对象statement
statement= conn.createStatement();
//执行sql
resultSet= statement.executeQuery(s);
if(resultSet.next==false){
System.out.println("列表中没有查询项");
}
resultSet.previous();//回到前一项数据,对上if的回溯
//循环读取
while(resultSet.next()){
//获取每一行的各列 的值
int ID=resultSet.getInt(1);
String account=resultSet.getString(2);
int balance=resultSet.getInt(3);
System.out.println(ID+"\t"+account+"\t"+balance);
}
} catch (SQLException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} finally {//关闭释放内存
if(resultSet!=null){
try {
resultSet.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(statement!=null){
try {
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(conn!=null){
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
}
标签:jdb mys close == previous com root style 数据库连接
原文地址:https://www.cnblogs.com/hpha/p/11455634.html