码迷,mamicode.com
首页 > 数据库 > 详细

Java连接数据库jdbc

时间:2019-09-03 22:24:13      阅读:126      评论:0      收藏:0      [点我收藏+]

标签: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();
}
}
}

}
}

Java连接数据库jdbc

标签:jdb   mys   close   ==   previous   com   root   style   数据库连接   

原文地址:https://www.cnblogs.com/hpha/p/11455634.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!