1 通过创建Driver接口,调用实例connect()方法来连接到数据库
import java.sql.SQLException;
import java.util.Properties;
import java.sql.*;
import com.mysql.jdbc.Driver;
public class Demo2 {
public static void main(String[] args) throws SQLException {
// TODO Auto-generated method stub
//创建一个MySQL数据库的驱动
Driver driver = new Driver();
//设置要连接到的数据库的信息
String url = "jdbc:mysql://localhost:3306/test";
Properties info = new Properties();
info.setProperty("user", "root");
info.setProperty("password", "s13562835851w");
//调用驱动的connect方法建立连接
Connection connection = driver.connect(url,info);
System .out.println("连接数据库成功 !!!"+connection );
}
}
2 加载DriverManager,通过驱动管理器getConnection()方法建立连接
import java.sql.Connection;
import java.sql.DriverManager;
public class Demo1 {
public static String className = "com.mysql.jdbc.Driver";
public static void main(String[] args) {
try {
//加载MYSQL JDBC驱动程序
Class.forName("com.mysql.jdbc.Driver");
System.out.println("Success loading Mysql Driver!");
}catch (Exception e)
{
System.out.print("Error loading Mysql Driver!");
e.printStackTrace();
}
try{
//连接URL为 jdbc:mysql//服务器地址/数据库名 ,后面的2个参数分别是登陆用户名和密码
String url = "jdbc:mysql://localhost:3306/test?characterEncoding=utf8&useSSL=true";
String username = "root";
String password = "s13562835851w";
//通过驱动管理器获得连接
Connection connection = DriverManager.getConnection(url,username,password);
System.out.println("Success connect Mysql server!!!\n"+connection);
}catch(Exception e)
{
System.out.print("get data error!");
e.printStackTrace();
}
}
}