import java.sql.Driver;
import java.sql.DriverManager;
import java.util.Properties;
import java.sql.Connection;
public class ConnectMysql{
private String url = "jdbc:mysql://localhost:3306/dinner";
private String user = "root";
private String password = "root";
/**
* 第一种连接方式
* @throws Exception
*/
public void test1() throws Exception{
//1.创建驱动程序类对象
Driver driver = new com.mysql.jdbc.Driver();
//2.设置用户名和密码
Properties props = new Properties();
props.setProperty("user", user);
props.setProperty("password", password);
//3.连接数据库,返回连接对象
Connection con = driver.connect(url, props);
//4.打印输出
System.out.println(con);
System.out.println("连接数据库的第一种方式\n");
}
/**
* 第二种连接方式
* @throws Exception
*/
public void test2() throws Exception{
Driver driver = new com.mysql.jdbc.Driver();
//1.注册驱动程序类对象
DriverManager.registerDriver(driver);
//2.链接到数据库
Connection con = DriverManager.getConnection(url,user,password);
//3.打印输出
System.out.println(con);
System.out.println("连接数据库的第二种方式\n");
}
/**
* 第三种链接方式 (建议使用的方式)
* @throws Exception
*/
public void test3() throws Exception{
//Driver driver = new com.mysql.jdbc.Driver();
//1.通过得到字节码对象的方式加载静态代码块,从而注册驱动程序
Class.forName("com.mysql.jdbc.Driver");
//2.连接到具体的数据库
Connection conn = DriverManager.getConnection(url, user, password);
//3.打印输出
System.out.println(conn);
}
public static void main(String[] args) {
ConnectMysql con1 = new ConnectMysql();
try{
con1.test1();
}catch(Exception e){}
ConnectMysql con2 = new ConnectMysql();
try{
con1.test2();
}catch(Exception e){}
ConnectMysql con3 = new ConnectMysql();
try{
con3.test3();
}catch(Exception e){}
}
}