数据库连接建立后返回值为connection类型因此通过
package com.amaker.util;
import java.sql.DriverManager;
import com.mysql.jdbc.Connection;
public class Tester {
private String url;
private String user;
private String password;
public Tester(String url, String user, String password) {
super();
this.url = url;
this.user = user;
this.password = password;
}
public Connection getconn(){
try{
Class.forName("com.mysql.jdbc.Driver"); //加载数据库连接驱动类
} catch ( ClassNotFoundException e)
{
e.printStackTrace();
}
try{
return (Connection) DriverManager.getConnection("jdbc:mysql://"+url, user, password); //获取并返回connection对象
} catch (Exception e)
{
e.printStackTrace();
}
return null;
}
}
方式定义链接数据库方法。返回具体类型为java.sql.Connection
连接过程中使用的getConnection参数有3种方式,此处使用第三种。
添加一个测试类测试数据库连接类是否正确,如下:
package com.amaker.util;
import org.junit.Test;
import com.mysql.jdbc.Connection;
public class runcon {
@Test
public void run(){
Tester con = new Tester("114.215.119.11:3306","root","123456");
Connection cnonn = con.getconn();
System.out.println("链接实例:"+cnonn );
}
}
测试运行成功后如图