JDBC创建连接的三种不同方式

    第一种:

//第一步:引包
import java.sql.*;


public class Jdbc {
  
static final String JDBC_Driver = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost:3306/jdbcdemo?useSSL=false";   //MySQL在高版本需要指明是否进行SSL连接

static final String user = "root";
static final String password = "root";

public static void main(String[] args){
   

Connection conn = null;
Statement st = null;

try {
    //第二步:注册驱动
    Class.forName("com.mysql.jdbc.Driver");
    //第三步:创建sql语句
    String sql = "select id,username,age,sex,phone from  sys_user";

    //第四步:创建连接
    conn = DriverManager.getConnection(DB_URL, user, password);           //url,username,password三个参数

    //第五步:执行查询
    st = conn.createStatement();                        //无参
    ResultSet rs = st.executeQuery(sql);

    //第六步:处理结果集
    while (rs.next()) {
        //通过列名获取值
        int id = rs.getInt("id");
        String username = rs.getString("username");
        int age = rs.getInt("age");
        String phone = rs.getString("phone");

        //打印
        System.out.print("ID: " + id);
        System.out.print(", 年龄: " + age);
        System.out.print(", 姓名: " + username);
        System.out.println(", 电话: " + phone);

    }
    rs.close();
}catch (SQLException se){
    se.printStackTrace();
}catch (Exception e){
    e.printStackTrace();
}finally {
    //第七步 释放资源
    try {
        if(st != null){
            st.close();
        }
    } catch (SQLException e) {
        e.printStackTrace();
    }
    try {
        if (conn != null) {
            conn.close();
        }
    } catch (SQLException e) {
        e.printStackTrace();
    }
}

}

}


第二种:原理同上。

static final String DB_URL = "jdbc:mysql://localhost:3306/jdbcdemo?user=root&password=root";

conn = DriverManager.getConnection(DB_URL);               //url一个参数

第三种:
Properties info = new Properties();     //定义Properties对象
info.setProperty("user","root");
info.setProperty("password","root");    //设置Properties对象属性

conn = DriverManager.getConnection(DB_URL,info);            //url,info  (info:是一个持久的属性集对象,包括user和password属性)



                               



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值