JDBC之连接数据库
Driver API
JDBC是一组API,主要包含Driver、Connection、Statement、ResultSet;在java.sql这个包下。
普通版
CMD命令:mysql -u root -p 123456 -D database_name;
Java代码:
//1. 创建一个 Driver 实现类的对象
Driver driver = new com.mysql.jdbc.Driver();
//2. 准备连接数据库的基本信息: url, user, password
String url = "jdbc:mysql://localhost:3306/mybatis";
Properties info = new Properties();
info.put("user", "root");
info.put("password", "123456");
//3. 调用 Driver 接口的 connect(url, info) 获取数据库连接
Connection connection = driver.connect(url, info);
改进版
以下方式有两个优点:1.配置信息写在属性文件里,修改配置以后不需要重新编译源代码;2.利用的反射的方式创建对象,不需要修改代码就可以更换数据库;
//读取类路径下的 jdbc.properties 文件
InputStream in = getClass().getClassLoader()
.getResourceAsStream("jdbc.properties");
Properties properties = new Properties();
properties.load(in);
String driverClass = properties.getProperty("driverClass");
String jdbcUrl = properties.getProperty("jdbcUrl");
String user = properties.getProperty("user");
String password = properties.getProperty("password");
//通过反射常见 Driver 对象.
Driver driver = (Driver) Class.forName(driverClass).newInstance();
Properties info = new Properties();
info.put("user", user);
info.put("password", password);
//通过 Driver 的 connect 方法获取数据库连接.
Connection connection = driver.connect(jdbcUrl, info);
最优版
Driver接口中的connect方法需要组装一个Properties参数,比较麻烦;建议采用DriverManager提供的getConnect方法来获取连接。
//读取类路径下的 jdbc.properties 文件
InputStream in = getClass().getClassLoader()
.getResourceAsStream("jdbc.properties");
Properties properties = new Properties();
properties.load(in);
String driverClass = properties.getProperty("driverClass");
String jdbcUrl=properties.getProperty("jdbcUrl");
String user=properties.getProperty("user");
String password=properties.getProperty("password");
//2. 加载数据库驱动程序(对应的 Driver 实现类中有注册驱动的静态代码块.)
Class.forName(driverClass);
//3. 通过 DriverManager 的 getConnection() 方法获取数据库连接.
Connection connection = DriverManager.getConnection(jdbcUrl, user, password);
jdbc.properties文件内容
driverClass=com.mysql.jdbc.Driver
jdbcUrl=jdbc:mysql://localhost:3306/mybatis
user=root
password=123456