java—JDBC链接数据库的4种方式

- 1. 根据 MYSQL 提供的驱动,获取与 MYSQL 数据库的连接

 @Test
	public void test1() throws Exception{
		//1. 获取驱动
		Driver driver = null;
		
		String driverClassName = "com.mysql.jdbc.Driver";
		
		Class clazz = Class.forName(driverClassName);
		
		driver = (Driver) clazz.newInstance();
		
		//2. 获取连接
		String url = "jdbc:mysql://127.0.0.1:3306/sys";
		Properties info = new Properties();
		info.setProperty("user", "root");
		info.setProperty("password", "123456");
		
		Connection conn = driver.connect(url, info);
		
		System.out.println(conn);
	}

- 2. 使用 DriverManager 驱动管理类,获取连接

@Test
	public void test2() throws Exception{
		String driverClassName = "com.mysql.jdbc.Driver";
		String url = "jdbc:mysql://127.0.0.1:3306/sys";
		String user = "root";
		String password = "123456";
		
		Driver driver = null;
		
		//1. 注册驱动(注册驱动,数据库厂商已经完成)
		Class clazz = Class.forName(driverClassName);
		
		driver = (Driver) clazz.newInstance();
		
		DriverManager.registerDriver(driver);
		
		//2. 获取连接
		Connection conn = DriverManager.getConnection(url, user, password);
		
		System.out.println(conn);
	}

- 3. 根据 DriverMz``anager 已经注册的驱动,获取连接

@Test
	public void test3() throws Exception{
		String driverClassName = "com.mysql.jdbc.Driver";
		String url = "jdbc:mysql://127.0.0.1:3306/sys";
		String user = "root";
		String password = "123456";
		
		//1. 加载驱动
		Class.forName(driverClassName);
		
		//2. 获取连接
		Connection conn = DriverManager.getConnection(url, user, password);
		
		System.out.println(conn);
		
	}

- 4. 获取 Properties 属性文件中的四个连接字符串

@Test
	public void test4() throws Exception{
		Properties props = new Properties();
		props.load(this.getClass().getClassLoader().getResourceAsStream("jdbc/jdbc.config"));
		String driverClassName = props.getProperty("driverClassName");
		String url = props.getProperty("url");
		String user = props.getProperty("user");
		String password = props.getProperty("password");
		
		//1. 加载驱动
		Class.forName(driverClassName);
		
		//2. 获取连接
		Connection conn = DriverManager.getConnection(url, user, password);
		
		System.out.println(conn);
	}
	
driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://127.0.0.1:3306/sys?rewriteBatchedStatements=true&useUnicode=true&characterEncoding=UTF-8

user=root
password=123456

#driverClassName=oracle.jdbc.driver.OracleDriver
#url=jdbc:oracle:thin:@127.0.0.1:1521:orcl
#user=scott
#password=tiger
  • 关于参数

characterEncoding=utf-8 //编码格式
autoReconnect=true//自动链接
useSSL=false//加密设置
rewriteBatchedStatements=true //支持批量导入注意使用批量导入时sql末尾不允许加“;”否则会报错
转载 https://blog.youkuaiyun.com/henryzhang2009/article/details/44175725

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值