package day01_jdbc;
import java.sql.Connection;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;
public class Demo01 {
// mysql
// 连接数据库的字符串
// url的格式:jdbc协议+数据库协议+主机地址+端口+连接的数据库
private static String url = "jdbc:mysql://localhost:3306/sakila";
private static String user = "root";
private static String password = "";
/*
// sql server
private static String url = "jdbc:sqlserver://localhost:1433;DatabaseName=MyDB";
private static String user = "sa";
private static String password = "123456";
*/
public static void main(String[] args) throws Exception {
// m1();
// m2();
m3();
}
private static void m3() throws SQLException, ClassNotFoundException {
/**
* 通过new的方式去注册驱动是有问题的
* 其实这样注册了两次驱动程序
*/
// Driver driver = new com.mysql.jdbc.Driver();
/**
* 反射:获取类的对象
*/
Class.forName("com.mysql.jdbc.Driver");
// 执行Driver类中的静态代码块
// 执行了上面的代码直接就将驱动注册到了驱动管理器中
Connection conn = DriverManager.getConnection(url, user, password);
System.out.println(conn);
}
private static void m2() throws SQLException {
Driver driver = new com.mysql.jdbc.Driver(); // mysql
// 1.注册驱动程序:注册驱动可同时注册多个
DriverManager.registerDriver(driver);
// DriverManager.registerDriver(driver2);
// 2.获取连接数据库
Connection conn = DriverManager.getConnection(url, user, password);
System.out.println(conn);
}
/**
* 1) 直接使用驱动程序连接
* @throws SQLException
*/
private static void m1() throws SQLException {
// 1.创建驱动程序的实现类对象
Driver driver = new com.mysql.jdbc.Driver(); // 新版本
// Driver driver = new org.gjt.mm.mysql.Driver(); // 旧版本
// Driver driver = new com.microsoft.sqlserver.jdbc.SQLServerDriver();
Properties prop = new Properties();
prop.setProperty("user", user); // 用户名
prop.setProperty("password", password);
// 2.连接数据库
Connection conn = driver.connect(url, prop);
System.out.println(conn);
}
}