Java JDBC(Java Database Connectivity)数据库连接规范

1.四个核心类
DriverManager --创建连接
Connection --连接类
Statement --执行SQL语句
ResultSet --结果集
2.JDBC连接的六个步骤
1)注册驱动
2)获取连接-Connection
3)获取sql语句的执行对象-Statement
4)执行sql语句,返回结果集-ResultSet
5)处理结果集
6)关闭资源
//查询语句
public class Demo01 {
    public static void main(String[] args) throws Exception {
 //1.注册驱动连接,用DriverManager类调用registerDriver(这里填写的是Driver匿名对象)方法,但是Driver里面有一个静态的代码块,当Driver这个类一加载就再次调用DriverManager.registerDriver(new com.mysql.jdbc.Driver());,所以不用这个了,直接将Driver类加载到内存中去,就可以了
 <!--DriverManager.registerDriver(new com.mysql.jdbc.Driver());-->
 //加载到内存中的格式:包名+类名
 Class.forName("com.mysql.jdbc.Driver");
//2.注册完驱动,获取连接对象
//这里有三种获取连接方式

//第一种
//url访问数据的连接地址
String url = "jdbc:mysql://localhost:3306/数据库名";
Connection connection = DriverManager.getConnection(url,"登录名","登录的密码");

//第二种---我们需要创建Properties集合
Properties info = new Properties();
//设置键值对/属性值
info.setProperty("user","root");//这里是设置用户名
info.setProperty("password","123456");//这里是设置密码的
Connection connection = DriverManager.getConnection(url,info);//这里把集合中的数据都传入获取连接的方法里

//第三种--使用get请求,携带参数,访问连接
String url1 ="jdbc:mysql://localhost:3306/数据库名?user=用户名&password=密码";
Connection connection = DriverManager.getConnection(null);

//3.获取执行sql语句的对象
Statement statement = connection.createStatement();

//4.执行sql语句并返回结果集

//注:这里结果集中所添加的索引,要和查询语句中的字段相对应

//这里是查询语句
String sql = "select * from users";
ResultSet resultSet = statement.executeQuery(sql);


//5.处理结果集,

while(resultSex.next()){
    System.out.println(resultSet.getObject(1));
         System.out.println(resultSet.getObject(2));
         System.out.println(resultSet.getObject(3));
         System.out.println(resultSet.getObject(4));
         System.out.println(resultSet.getObject(5));
         System.out.println("_____________________"); 
}

//6.关闭资源
resultSet.close();
statement.close();
connection.close();
//增删改查语句

public class DemoCRUD{
//注解:用来测试方法
    @Test 
  public void test throws Exception{
      Class.forName("com.mysql.jdbc.Driver");
      String url = "jdbc:mysql://localhost:3306/myjdbc"

   Connection connection = DriverManager.getConnection(url,"root","123455");
   Statement statement = connection.createStatement();

  //这里是添加数据
   String  sql ="insert into users values(2,'gs','123','123@qq.com','1993-1-1')";

  //statement.executeUpdate();sql执行对象调用更新方法,这个方式也是删除的方法



  int  row = statement.executeUpdate(sql);
 //这里返回的row表示受影响的行数
 //我们可以通过受影响行数来判断是否执行成功
 if(row>0){
     System.out.println("插入成功");
 }
  }
}
//连接数据库连接异常处理
//这里我们把结果集的每条记录当做对象放到集合当中,所以我们先创建一个对象,将一条记录的每一列添加到对象中

//创建一个User对象
public class User {
 //我们设置是,对于对象中的属性名,尽量和数据库中的字段名相同,不容易出错
    private int id;
    private String name;
    private String password;
    private String email;
    private Date birthday;

    public User() {
        super();
    }

    public User(int id, String name, String password, String email, Date birthday) {
        super();
        this.id = id;
        this.name = name;
        this.password = password;
        this.email = email;
        this.birthday = birthday;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public Date getBirthday() {
        return birthday;
    }

    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }

    @Override
    public String toString() {
        return "User[id=" + id + ", name=" + name + ", password=" + password + ", email=" + email + ", birthday="
                + birthday + "]";
    }

}


public class DemoException {
 public static void main(String[] args) {
 Connection connection = null;
 Statement statement = null;
 ResultSet resultSet = null;
 try{
     //这里会有加载驱动失败异常
     Class.forName("com.mysql.jdbc.Driver");
    //这里是连接数据库异常
    String url = "jdbc:mysql://localhos:3306/myjdbc";
    connection = DriverManager.getConnection(url,"root","123456");
    statement = connection.createStatement();
    String sql = "select * from users";
    resultSet = statement.executeQuery(sql);
  //创建一个集合,用于存储每条记录的当做一个对象的集合
  ArrayList<User> list = new ArrayList<>();
  while(resultSet.next()){
     //这里我们创建User对象,并通过结果集对象调用获取方法对应的给对象的变量赋值
     User user = new User();
     user.setId(resultSet.getInt("id"));
     user.setName(resultSet.getString("name"));
     user.setPassword(resultSet.getString("password"));
     user.setEmail(resultSet.getString("email"));
     user.setBirthday(resultSet.getDate("birthday"));
    //赋值完毕,添加到集合中
    list.add(user);

  }
  //遍历打印集合中的对象数据
  for(User user :list){
      System.out.println(user);

  }
 } catch (SQLException e) {
         e.printStackTrace();
            throw new RuntimeException("获取连接失败");
        }
     catch (ClassNotFoundException e) {
         e.printStackTrace();
        throw new RuntimeException("驱动加载失败");
    }finally {

    }

}
}
//这里将,获取数据库的连接方法,连接数据库异常,建立工具类便于调用
//首先,我们要先创建一个配置文件
//1.在src下创建一个文本文件,这里起名一般保存的后缀名是.properties,dbinfo.properties(文本名)
//2.数据是:
driverClass=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/myjdbc
user=root
password=123456


public class JDBCUtil {
 private static String driverClass;
 private static String url;
 private static String user;
 private static String password;
 //第一种,先使用集合读取文件
 Properties properties = new Properties();
 try{
     FileInputStream fis = new FileInputStream("src/dbinfo.propeerties");//注:这里后缀要写全
     properties.load(fis);
    //根据键读取对应的值
    driverClass = properties,getProperty("driverClass");
    url = properties.getProperty("url");
    user = properties.getProperty("user");
    password = properties.getProperty("password");
    }catech (Exception e) {
            e.printStackTrace();
        }
//第二种,使用系统类来读取配置文件
//我们在静态代码块里编写读取配置文件
ResourceBundle rb = ResourceBundle.getBundle("dbinfo");//注:这里的后缀不写
//获取文件中的数据
driverClass = rb.getString("driverClass");
url = rb.getString("url");
user = rb.getString("user");
password = rb.getString("password");

//这里加载驱动,静态代码块只加载一次
try {
             //驱动加载失败异常
            Class.forName(driverClass);
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
//获取数据库连接的方法
public static Connection getConnection() throws SQLException {
   return DriverManager.getConnection(url,user,password);
   }
  //关闭数据库的方法
 public static void closeAll(ResultSet resultSet,Statement statement,Connection connection){
    //这里关闭资源前,要先做非空判断才能确定关闭资源否
    if(resultSet != null){
        try{
            resultSet.close();
        }catch (SQLException e){
            throw new RuntimeException("关闭失败");
        }
        resultSet = null;//这里是将结果集清空,加快系统回收速度
    }if(connection != null) {
                try {
                    connection.close();

                } catch (SQLException e) {
                    throw new RuntimeException("关闭失败");
                }
                connection = null;
            }
            if(statement != null) {
                try {
                    statement.close();
                } catch (SQLException e) {
                    throw new RuntimeException("关闭失败");
                }
        //这里清空数据处理对象,便于加快系统垃圾回收
                statement = null;
            }   
     }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值