Web工程中建立class文件:
package cn.edu.hpu.jdbc;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class JDBC {
private String username="root";
private String password="ljy";
private String url="jdbc:mysql://localhost:3306/ljy";
private Connection conn=null;
public Connection getconn(){
try {
Class.forName("org.gjt.mm.mysql.Driver");
conn = DriverManager.getConnection(url, username, password);
} catch (Exception e) {
e.printStackTrace();
}
return conn;
}
}
另外再建立一个class文件,用于检测是否连接成功:
package cn.edu.hpu.jdbc;
import java.sql.Connection;;
public class JdbcTest {
public static void main(String[] args) {
JDBC db=new JDBC();
Connection conn=db.getconn();
if(conn!=null){
System.out.println("Success");
}else{
System.out.println("Failure");
}
}
}
如果返回success,则连接成功!