JDBC的五种连接方式

JDBC的五种连接方式

1.直接实例化Driver

Driver driver=new com.mysql.jdbc.Driver();
String url="jdbc:myslq://local:3306/database";
Properties info=new Properties();
info.setProperty("user","root");
info.setProperty("password","****");
Connection con=driver.connect(url,info);

2.反射实现Driver类

//更具有通用性
Class clazz=Class.forName("com.mysql.jdbc.Driver");
Driver driver=(Driver)clazz.newInstance();
String url="jdbc:myslq://local:3306/database";
Properties info=new Properties();
info.setProperty("user","root");
info.setProperty("password","****");
Connection con=driver.connect(url,info);

3.使用DriverManager替换Driver接口

Class clazz=Class.forName("com.mysql.jdbc.Driver");
Driver driver=(Driver)clazz.newInstance();
//注册驱动
DriverManager.registerDriver(driver);
String url="jdbc:myslq://local:3306/database";
String user="root";
String password="****";
Connection con=DriverManager.getConnection(url,user,password);

4.利用mysql的driver实现类自动进行了注册驱动,直接调用DriverManager的静态方法连接

//省略注册驱动
//在MySQL的driver实现类的静态代码块中已进行了方法三的操作
Class.forName("com.mysql.jdbc.Driver");//mysql这句也可以省
String url="jdbc:myslq://local:3306/database";
String user="root";
String password="****";
Connection con=DriverManager.getConnection(url,user,password);

5.将连接的四个基本信息声明在配置文件中,读取配置文件进行连接
jdbc.properties

driverClass=com.jdbc.mysql.Driver
user=root
password=****
url=jdbc:mysql://localhost:3306/database
//数据和代码分离,如有修改只需修改配置文件
InputStream is =JDBCUtils.class.getClassLoader().getResourceAsStream("config.properties");
Properties prop=new Properties();
prop.load(is);

String driverClass= prop.getProperty("driverClass");
String url=prop.getProperty("url");
String user=prop.getProperty("username");
String password= prop.getProperty("password");
Class.forName(driverClass);
Connection con=DriverManager.getConnection(url,user,password);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值