数据库连接的5种方式
String url = "jdbc:mysql://localhost:3306/njustzjc1";
Properties properties = new Properties();
properties.setProperty("user","root");
properties.setProperty("password","zjc");
Driver driver = new Driver();
Connection connect = driver.connect(url, properties);
String sql = "insert into jdbc values(1,'zjc')";
Statement statement = connect.createStatement();
int i = statement.executeUpdate(sql);
statement.close();
connect.close();
String path = "com.mysql.jdbc.Driver";
Class<?> aClass = Class.forName(path);
Object oo = aClass.newInstance();
Driver o = (Driver) oo;
String url = "jdbc:mysql://localhost:3306/njustzjc1";
Properties properties = new Properties();
properties.setProperty("user","root");
properties.setProperty("password","zjc");
Connection connect = o.connect(url, properties);
String sql = "delete from jdbc where id = 1";
Statement statement = connect.createStatement();
int i = statement.executeUpdate(sql);
System.out.println(i > 0 ? "成功":"失败");
statement.close();
connect.close();
//方式3 使用DriverManager 替代 driver 进行统一管理
@Test
public void connect03() throws IllegalAccessException, InstantiationException, ClassNotFoundException, SQLException {
//使用反射加载Driver
Class<?> aClass = Class.forName("com.mysql.jdbc.Driver");
Driver driver = (Driver) aClass.newInstance();
//创建url 和 user 和 password
String url = "jdbc:mysql://localhost:3306/hsp_db02";
String user = "root";
String password = "hsp";
DriverManager.registerDriver(driver);//注册Driver驱动
Connection connection = DriverManager.getConnection(url, user, password);
System.out.println("第三种方式=" + connection);
}
更简单的方式:
底层有静态代码块帮助我们完成了registerdriver的事情
//创建url 和 user 和 password
String url = "jdbc:mysql://localhost:3306/hsp_db02";
String user = "root";
String password = "hsp";
Connection connection = DriverManager.getConnection(url, user, password);
System.out.println("第4种方式~ " + connection);
}
//方式5 , 在方式4的基础上改进,增加配置文件,让连接mysql更加灵活
@Test
public void connect05() throws IOException, ClassNotFoundException, SQLException {
//通过Properties对象获取配置文件的信息
Properties properties = new Properties();
properties.load(new FileInputStream("src\\mysql.properties"));
//获取相关的值
String user = properties.getProperty("user");
String password = properties.getProperty("password");
String driver = properties.getProperty("driver");
String url = properties.getProperty("url");
Class.forName(driver);//建议写上
Connection connection = DriverManager.getConnection(url, user, password);
System.out.println("方式5 " + connection);
- class.forname()实际上可以不写
- url的解释: