我创建了一个带有登录信息帐户(用户名,密码)的java web。现在我想使用 MySQL ver5.6 连接到数据库。我已经拥有包含 id、用户名、密码的数据库。
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");
}
}
}
最佳答案
公共(public)类数据库{
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;
}
关于java - 使用MySQL将web java连接到数据库系统,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26878923/