我已通过管理控制台配置了GlassFish Server,并添加了JDBC连接池和JDBC资源。从GlassFish ping管理控制台可以获得成功。我正在创建Database对象并从Database类调用插入方法。
Database database = new Database();
BigInteger acSerial = att.getSerialNumber();
BigInteger pkcSerial = att.getHolder().getSerialNumber();
String AC = Base64.getUrlEncoder().encodeToString(att.getEncoded());
database.inserting(acSerial,pkcSerial,AC);
这是我在Database类中的插入方法:
public class Database {
// JDBC driver name and database URL
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost:3306/AC?autoReconnect=true&useSSL=false";
// Database credentials
static final String USER = "XXXXXX";
static final String PASS = "XXXXXXXX";
public void inserting(BigInteger acparam, BigInteger pkcparam, String encoded) {
Connection conn = null;
Statement stmt = null;
try{
//STEP 2: Register JDBC driver
Class.forName("com.mysql.jdbc.Driver");
//STEP 3: Open a connection
conn = DriverManager.getConnection(DB_URL, USER, PASS);
//STEP 4: Execute a query
stmt = conn.createStatement();
String sql = "INSERT INTO ACCredentials " + "VALUES (" +acparam +"," +pkcparam +"," +"'"+encoded+"'" +")" + "";
stmt.executeUpdate(sql);
}catch(SQLException se){
//Handle errors for JDBC
se.printStackTrace();
}catch(Exception e){
//Handle errors for Class.forName
e.printStackTrace();
}finally{
//finally block used to close resources
try{
if(stmt!=null)
conn.close();
}catch(SQLException se){
}
try{
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
}
}
}
}
我的问题是没有插入MySQL数据库。我尝试过这个没有GlassFish Server的插入示例,但它确实有效。有人知道这个问题吗?
答案 0 :(得分:0)
我实际上解决了这个问题。我忘记了DataSource部分:
public void inserting(BigInteger acparam, BigInteger pkcparam, String encoded) throws NamingException {
InitialContext ctx;
DataSource ds;
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
ctx = new InitialContext();
ds = (DataSource) ctx.lookup("jdbc/MeinDatasourceJndiName");
//ds = (DataSource) ctx.lookup("jdbc/MySQLDataSource");
conn = ds.getConnection();
stmt = conn.createStatement();
String sql = "INSERT INTO ACCredentials " + "VALUES (" +acparam +"," +pkcparam +"," +"'"+encoded+"'" +")" + "";
//rs = stmt.executeQuery(sql);
stmt.executeUpdate(sql);
while(rs.next()) {
}
}
catch (SQLException se) {
}