Java DriverManager. Getconnection() method: get database connection

Grammar 1

getConnection(String url)

Example

public Connection getConnection(){
    Connection con=null;
    try{
      Class.forName("com.MysqL.jdbc.Driver");  //注册数据库驱动
      String url = "jdbc:MysqL://localhost:3306/test?user=root&password=root";  //定义连接数据库的url
      con = DriverManager.getConnection(url);  //获取数据库连接
      System.out.println("数据库连接成功!");
    }catch(Exception e){
      e.printStackTrace();
    }
      return con;  //返回一个连接
}

Grammar 2

getConnection(String url,Properties info)

Example

public Connection getConnection(){
    Connection con = null;  //定义数据库连接对象
    Properties info = new Properties();  //定义Properties对象
    info.setProperty("user","root");  //设置Properties对象属性
    info.setProperty("password","root");
    try{
      Class.forName("com.MysqL.jdbc.Driver");  //注册数据库驱动
      String url = "jdbc:MysqL://localhost:3306/test";  //test为数据库名称
      con = DriverManager.getConnection(url,info);  //获取连接数据库的Connection对象
      System.out.println("数据库连接成功!");
    }catch(Exception e){
      e.printStackTrace();
    }
      return con;//返回一个连接
}

Grammar 3

Connection(String url,String user,String password)

Typical application

private Connection con;
private String user = "sa";  //定义连接数据库的用户名
private String password = "";  //定义连接数据库的密码
private String className = "com.microsoft.sqlserver.jdbc.sqlServerDriver";
private String url = "jdbc:sqlserver://localhost:1433;DatabaseName=db_database01";  /**创建数据库连接*/
public Connection getCon(){
  try{
    Class.forName(className);//加载数据库驱动
    System.out.println("数据库驱动加载成功!");
    con = DriverManager.getConnection(url,user,password);  //连接数据库
    System.out.println("成功地获取数据库连接!");
  }catch(Exception e){
    System.out.println("创建数据库连接失败!");
    con = null;
    e.printStackTrace();
  }
  return con;
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>