JDBC连接数据库的几种方式

方式一:

public class connectOne{
	public static void main(){
		Driver driver=new com.mysql.jdbc.Driver();    //导入mysql的jdbc驱动
		String usl="jdbc:mysql://localhost:3306/test"     //获取mysql地址
		
		Properties info=new Properties();                 //建立一个Properties属性列表
		info.setProperty("user","root");                  //传入用户名和密码
		info.setProperty("password","password");
		
		Connection conn=driver.connect(url,info);          //建立连接

		System.out.println(conn);                
}
}

方式一连接方式简单,但是需要外部的驱动来支持

方式二:

public class connectTwo{
	public static void main(){
		//实例化Driver
		String className="com.mysql.jdbc.Driver";
		Class clazz=Class.forName(className);
		Driver driver=(Driver)clazz.newInstance();
		
		//给出数据库地址
		String url="jdbc:mysql://localhost:3306/test";
		
		//建立属性列,给出用户名和密码
		Properties info=new Properties();
		info.setProperty("user","root");           
		info.setProperty("password","password");

		Connection conn=driver.connect(url,info);
}

方式二不需要第三方的API

方式三:

public class connectThree{
	public static void main(){
		String url="jdbc:mysql"//localhost:3306/test";
		String user="root";
		String password="password";
		String driverName="com.mysql.jdbc.Driver";

		//实例化Driver
		Class clazz=Class.forName(driverName);
		Driver driver=(Driver)clazz.newInstance();
		
		//注册驱动
		DriverManager.registerDriver(driver);
		
		//获取连接
		Connection conn=DriverManager.getConnection(url,user,password);
		
}

使用DriverManager连接数据库

方式四:

public class connectFour{
	public static void main(){
		String url="jdbc:mysql"//localhost:3306/test";
		String user="root";
		String password="password";
		String driverName="com.mysql.jdbc.Driver";

		//加载驱动
		Class.forName(driverName);

		//建立连接
		Connection conn =DriverManager.getConnection(url,user,password);
		
}

不必注册驱动,DriverManager已经实现了驱动注册

方式五:

public class connectFive{
	public static void main(){
		//加载配置文件
		InputStream is=connectFive.getClassLoader().getResourceAsStream("jdbc.properties")
		Properties pros=new Properties();
		pros.load(is);

		//读取配置信息
		String user = ppros,getProperty("user");
		String pass=pros.getProperty("password");
        String url=pros.getProperty("url");
        String driver=pros.getProperty("driverClass");

		//加载驱动
		Class.forName(driver);

		//获取链接
		Connection conn=DriverManager.getConnection(url,user,password);	
}

其中配置文件声明在src目录下jdbc.properties

user=root
password=abc123
url=jdbc:mysql://localhost:3306/test
driverClass=com.mysql.jdbc.Driver

实现数据与代码分离,方便管理,可以将其封装,后续直接调用。

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值