获取数据库连接方式
package learn_jdbc;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;
public class learn_jdbc3 {
public static void main(String[] args) throws Exception
{
//方式1
Driver driver=new com.mysql.jdbc.Driver();
String url="jdbc:mysql://localhost:3306/atguigudb";
String password="123456";
//将用户名和密码封装在Properties中
Properties info=new Properties();
info.setProperty("user","root");
info.setProperty("password","123456");
Connection connect = driver.connect(url, info);
System.out.println(connect);
//方式2:对方式1的迭代 :在如下的程序中不出现第三方的api,使得程序具有更好的可移植性
// 1. 获取Driver实现类对象,使用反射
Class<?> aClass = Class.forName("com.mysql.jdbc.Driver");
Driver driver = (Driver) aClass.newInstance();
//2. 提供要连接的数据库
String url="jdbc:mysql://localhost:3306/atguigudb";
String password="123456";
//3. 将用户名和密码封装在Properties中
Properties info=new Properties();
info.setProperty("user","root");
info.setProperty("password","123456");
//4. 获取连接
Connection connect = driver.connect(url, info);
System.out.println(connect);
//方式3:使用DriverManager替换Driver
//1. 获取Driver实现类的对象
Class<?> aClass = Class.forName("com.mysql.jdbc.Driver");
Driver driver = (Driver) aClass.newInstance();
2. 提供数据库连接的基本信息
String url="jdbc:mysql://localhost:3306/atguigudb";
String user="root";
String password="123456";
//注册驱动
DriverManager.registerDriver(driver);
//获取连接
Connection connection = DriverManager.getConnection(url, user, password);
System.out.println(connection);
//方式4:
//加载驱动
//静态代码块什么时候执行:随着类的加载而执行
/*