我创建了一个带有登录信息帐户(用户名,密码)的java网站。现在我想使用MySQL ver5.6连接到数据库。我已经拥有id,userName,password的数据库。
package dao;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public abstract class DBConnectionDAO {
/** Connection */
protected Connection connection;
/** className */
private String className = "com.mysql.jdbc.Driver";
/** stringConnection */
private String stringConnection = "jdbc:mysql://localhost/test?user=root&password=abc123&characterEncoding=UTF-8";
/**
* @Constructor Phuong thuc khoi tao
*/
public DBConnectionDAO() {
try {
Class.forName(className);
// Open connection
connection = DriverManager.getConnection(stringConnection);
} catch (ClassNotFoundException e) {
System.err.println("Class not found! Please review your library");
} catch (SQLException e) {
e.printStackTrace();
System.err.println("Loi truy van");
}
}
}
答案 0 :(得分:0)
公共类数据库{
Connection conn = null;
int id;
static{
try {
Class.forName("com.mysql.jdbc.Driver");
System.out.println("Driver Loaded Successfully..");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
public Connection connect(){
try {
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/databasename", "root", "root");
if(conn!=null)
{
System.out.println("Database Connected Successfully...");
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return conn;
}