GVKun编程网logo

com.mysql.jdbc.CommunicationsException的实例源码

1

在本文中,我们将带你了解com.mysql.jdbc.CommunicationsException的实例源码在这篇文章中,同时我们还将给您一些技巧,以帮助您实现更有效的centos7设置mysql自

在本文中,我们将带你了解com.mysql.jdbc.CommunicationsException的实例源码在这篇文章中,同时我们还将给您一些技巧,以帮助您实现更有效的centos7 设置 mysql 自启动的配置文件中 [Service] User=mysql Group=mysql,user 和 group 这边的 mysql 是指的什么?centos 的登录用户名?、com.mysql.jdbc.Driver to com.mysql.cj.jdbc.Driver、com.mysql.jdbc.Driver 与 org.gjt.mm.mysql.Driver的区别、com.mysql.jdbc.Driver 和 com.mysql.cj.jdbc.Driver 的区别

本文目录一览:

com.mysql.jdbc.CommunicationsException的实例源码

com.mysql.jdbc.CommunicationsException的实例源码

项目:the-vigilantes    文件:MysqLConnectionTester.java   
public int statusOnException(Connection arg0,Throwable throwable) {
    if (throwable instanceof CommunicationsException || "com.MysqL.jdbc.exceptions.jdbc4.CommunicationsException".equals(throwable.getClass().getName())) {
        return CONNECTION_IS_INVALID;
    }

    if (throwable instanceof sqlException) {
        String sqlState = ((sqlException) throwable).getsqlState();

        if (sqlState != null && sqlState.startsWith("08")) {
            return CONNECTION_IS_INVALID;
        }

        return CONNECTION_IS_OKAY;
    }

    // Runtime/Unchecked?

    return CONNECTION_IS_INVALID;
}
项目:OpenVertretung    文件:MysqLConnectionTester.java   
public int statusOnException(Connection arg0,Throwable throwable) {
    if (throwable instanceof CommunicationsException || "com.MysqL.jdbc.exceptions.jdbc4.CommunicationsException".equals(throwable.getClass().getName())) {
        return CONNECTION_IS_INVALID;
    }

    if (throwable instanceof sqlException) {
        String sqlState = ((sqlException) throwable).getsqlState();

        if (sqlState != null && sqlState.startsWith("08")) {
            return CONNECTION_IS_INVALID;
        }

        return CONNECTION_IS_OKAY;
    }

    // Runtime/Unchecked?

    return CONNECTION_IS_INVALID;
}
项目:lams    文件:MysqLConnectionTester.java   
public int statusOnException(Connection arg0,Throwable throwable) {
    if (throwable instanceof CommunicationsException || "com.MysqL.jdbc.exceptions.jdbc4.CommunicationsException".equals(throwable.getClass().getName())) {
        return CONNECTION_IS_INVALID;
    }

    if (throwable instanceof sqlException) {
        String sqlState = ((sqlException) throwable).getsqlState();

        if (sqlState != null && sqlState.startsWith("08")) {
            return CONNECTION_IS_INVALID;
        }

        return CONNECTION_IS_OKAY;
    }

    // Runtime/Unchecked?

    return CONNECTION_IS_INVALID;
}
项目:ProyectoPacientes    文件:MysqLConnectionTester.java   
public int statusOnException(Connection arg0,Throwable throwable) {
    if (throwable instanceof CommunicationsException || "com.MysqL.jdbc.exceptions.jdbc4.CommunicationsException".equals(throwable.getClass().getName())) {
        return CONNECTION_IS_INVALID;
    }

    if (throwable instanceof sqlException) {
        String sqlState = ((sqlException) throwable).getsqlState();

        if (sqlState != null && sqlState.startsWith("08")) {
            return CONNECTION_IS_INVALID;
        }

        return CONNECTION_IS_OKAY;
    }

    // Runtime/Unchecked?

    return CONNECTION_IS_INVALID;
}
项目:BibliotecaPS    文件:MysqLConnectionTester.java   
public int statusOnException(Connection arg0,Throwable throwable) {
    if (throwable instanceof CommunicationsException || "com.MysqL.jdbc.exceptions.jdbc4.CommunicationsException".equals(throwable.getClass().getName())) {
        return CONNECTION_IS_INVALID;
    }

    if (throwable instanceof sqlException) {
        String sqlState = ((sqlException) throwable).getsqlState();

        if (sqlState != null && sqlState.startsWith("08")) {
            return CONNECTION_IS_INVALID;
        }

        return CONNECTION_IS_OKAY;
    }

    // Runtime/Unchecked?

    return CONNECTION_IS_INVALID;
}
项目:Geometry-wars    文件:MysqLConnectionTester.java   
public int statusOnException(Connection arg0,Throwable throwable) {
    if (throwable instanceof CommunicationsException || "com.MysqL.jdbc.exceptions.jdbc4.CommunicationsException".equals(throwable.getClass().getName())) {
        return CONNECTION_IS_INVALID;
    }

    if (throwable instanceof sqlException) {
        String sqlState = ((sqlException) throwable).getsqlState();

        if (sqlState != null && sqlState.startsWith("08")) {
            return CONNECTION_IS_INVALID;
        }

        return CONNECTION_IS_OKAY;
    }

    // Runtime/Unchecked?

    return CONNECTION_IS_INVALID;
}
项目:TPKB    文件:MysqLConnectionTester.java   
public int statusOnException(Connection arg0,Throwable throwable) {
    if (throwable instanceof CommunicationsException || "com.MysqL.jdbc.exceptions.jdbc4.CommunicationsException".equals(throwable.getClass().getName())) {
        return CONNECTION_IS_INVALID;
    }

    if (throwable instanceof sqlException) {
        String sqlState = ((sqlException) throwable).getsqlState();

        if (sqlState != null && sqlState.startsWith("08")) {
            return CONNECTION_IS_INVALID;
        }

        return CONNECTION_IS_OKAY;
    }

    // Runtime/Unchecked?

    return CONNECTION_IS_INVALID;
}
项目:cloudera-cli-scripts    文件:MysqLConnectionTester.java   
public int statusOnException(Connection arg0,Throwable throwable) {
    if (throwable instanceof CommunicationsException || "com.MysqL.jdbc.exceptions.jdbc4.CommunicationsException".equals(throwable.getClass().getName())) {
        return CONNECTION_IS_INVALID;
    }

    if (throwable instanceof sqlException) {
        String sqlState = ((sqlException) throwable).getsqlState();

        if (sqlState != null && sqlState.startsWith("08")) {
            return CONNECTION_IS_INVALID;
        }

        return CONNECTION_IS_OKAY;
    }

    // Runtime/Unchecked?

    return CONNECTION_IS_INVALID;
}
项目:resource_access_tools    文件:AbstractObrDao.java   
/**
 * Executes a given sql query as String using a generic statement.
 * Fetch resultset row by row (cf. MysqL JDBC driver doc).
 * As it returns a ResultSet,this statement needs to be explicitly closed after the processing of the ResultSet with function
 * {see closeTableStatement()}.
 * Attention,no other use of the connection must be done before the generic table statement to be closed.
 */
protected ResultSet executesqlQueryWithFetching(String query) throws sqlException {
    ResultSet rSet;
    try {
        tableStatement = tableConnection.createStatement(ResultSet.TYPE_FORWARD_ONLY,ResultSet.CONCUR_READ_ONLY);
        tableStatement.setFetchSize(Integer.MIN_VALUE);
        rSet = tableStatement.executeQuery(query);
    } catch (CommunicationsException e) {
        reOpenConnectionIfClosed();
        tableStatement = tableConnection.createStatement(ResultSet.TYPE_FORWARD_ONLY,ResultSet.CONCUR_READ_ONLY);
        tableStatement.setFetchSize(Integer.MIN_VALUE);
        rSet = tableStatement.executeQuery(query);
    }
    //logger.info("query: " + query);
    return rSet;
}
项目:fil_project_mgmt_app_v2    文件:MysqLConnectionTester.java   
public int statusOnException(Connection arg0,Throwable throwable) {
    if (throwable instanceof CommunicationsException
            || "com.MysqL.jdbc.exceptions.jdbc4.CommunicationsException"
                    .equals(throwable.getClass().getName())) {
        return CONNECTION_IS_INVALID;
    }

    if (throwable instanceof sqlException) {
        String sqlState = ((sqlException) throwable).getsqlState();

        if (sqlState != null && sqlState.startsWith("08")) {
            return CONNECTION_IS_INVALID;
        }

        return CONNECTION_IS_OKAY;
    }

    // Runtime/Unchecked?

    return CONNECTION_IS_INVALID;
}
项目:indoor-tracking    文件:MysqLConnectionTester.java   
public int statusOnException(Connection arg0,Throwable throwable) {
    if (throwable instanceof CommunicationsException
            || "com.MysqL.jdbc.exceptions.jdbc4.CommunicationsException"
                    .equals(throwable.getClass().getName())) {
        return CONNECTION_IS_INVALID;
    }

    if (throwable instanceof sqlException) {
        String sqlState = ((sqlException) throwable).getsqlState();

        if (sqlState != null && sqlState.startsWith("08")) {
            return CONNECTION_IS_INVALID;
        }

        return CONNECTION_IS_OKAY;
    }

    // Runtime/Unchecked?

    return CONNECTION_IS_INVALID;
}
项目:SMPT42    文件:MysqLConnectionTester.java   
public int statusOnException(Connection arg0,Throwable throwable) {
    if (throwable instanceof CommunicationsException || "com.MysqL.jdbc.exceptions.jdbc4.CommunicationsException".equals(throwable.getClass().getName())) {
        return CONNECTION_IS_INVALID;
    }

    if (throwable instanceof sqlException) {
        String sqlState = ((sqlException) throwable).getsqlState();

        if (sqlState != null && sqlState.startsWith("08")) {
            return CONNECTION_IS_INVALID;
        }

        return CONNECTION_IS_OKAY;
    }

    // Runtime/Unchecked?

    return CONNECTION_IS_INVALID;
}
项目:ForYou    文件:MysqLConnectionTester.java   
public int statusOnException(Connection arg0,Throwable throwable) {
    if (throwable instanceof CommunicationsException
            || "com.MysqL.jdbc.exceptions.jdbc4.CommunicationsException"
                    .equals(throwable.getClass().getName())) {
        return CONNECTION_IS_INVALID;
    }

    if (throwable instanceof sqlException) {
        String sqlState = ((sqlException) throwable).getsqlState();

        if (sqlState != null && sqlState.startsWith("08")) {
            return CONNECTION_IS_INVALID;
        }

        return CONNECTION_IS_OKAY;
    }

    // Runtime/Unchecked?

    return CONNECTION_IS_INVALID;
}
项目:group-five    文件:MysqLConnectionTester.java   
public int statusOnException(Connection arg0,Throwable throwable) {
    if (throwable instanceof CommunicationsException || "com.MysqL.jdbc.exceptions.jdbc4.CommunicationsException".equals(throwable.getClass().getName())) {
        return CONNECTION_IS_INVALID;
    }

    if (throwable instanceof sqlException) {
        String sqlState = ((sqlException) throwable).getsqlState();

        if (sqlState != null && sqlState.startsWith("08")) {
            return CONNECTION_IS_INVALID;
        }

        return CONNECTION_IS_OKAY;
    }

    // Runtime/Unchecked?

    return CONNECTION_IS_INVALID;
}
项目:locaviewer    文件:MysqLConnectionTester.java   
public int statusOnException(Connection arg0,Throwable throwable) {
    if (throwable instanceof CommunicationsException || "com.MysqL.jdbc.exceptions.jdbc4.CommunicationsException".equals(throwable.getClass().getName())) {
        return CONNECTION_IS_INVALID;
    }

    if (throwable instanceof sqlException) {
        String sqlState = ((sqlException) throwable).getsqlState();

        if (sqlState != null && sqlState.startsWith("08")) {
            return CONNECTION_IS_INVALID;
        }

        return CONNECTION_IS_OKAY;
    }

    // Runtime/Unchecked?

    return CONNECTION_IS_INVALID;
}
项目:manydesigns.cn    文件:MysqLConnectionTester.java   
public int statusOnException(Connection arg0,Throwable throwable) {
    if (throwable instanceof CommunicationsException
            || "com.MysqL.jdbc.exceptions.jdbc4.CommunicationsException"
                    .equals(throwable.getClass().getName())) {
        return CONNECTION_IS_INVALID;
    }

    if (throwable instanceof sqlException) {
        String sqlState = ((sqlException) throwable).getsqlState();

        if (sqlState != null && sqlState.startsWith("08")) {
            return CONNECTION_IS_INVALID;
        }

        return CONNECTION_IS_OKAY;
    }

    // Runtime/Unchecked?

    return CONNECTION_IS_INVALID;
}
项目:Gladiatus    文件:MysqLConnectionTester.java   
public int statusOnException(Connection arg0,Throwable throwable) {
    if (throwable instanceof CommunicationsException
            || "com.MysqL.jdbc.exceptions.jdbc4.CommunicationsException"
                    .equals(throwable.getClass().getName())) {
        return CONNECTION_IS_INVALID;
    }

    if (throwable instanceof sqlException) {
        String sqlState = ((sqlException) throwable).getsqlState();

        if (sqlState != null && sqlState.startsWith("08")) {
            return CONNECTION_IS_INVALID;
        }

        return CONNECTION_IS_OKAY;
    }

    // Runtime/Unchecked?

    return CONNECTION_IS_INVALID;
}
项目:Jspad    文件:MysqLConnectionTester.java   
public int statusOnException(Connection arg0,Throwable throwable) {
    if (throwable instanceof CommunicationsException
            || "com.MysqL.jdbc.exceptions.jdbc4.CommunicationsException"
                    .equals(throwable.getClass().getName())) {
        return CONNECTION_IS_INVALID;
    }

    if (throwable instanceof sqlException) {
        String sqlState = ((sqlException) throwable).getsqlState();

        if (sqlState != null && sqlState.startsWith("08")) {
            return CONNECTION_IS_INVALID;
        }

        return CONNECTION_IS_OKAY;
    }

    // Runtime/Unchecked?

    return CONNECTION_IS_INVALID;
}
项目:Trails    文件:MysqLConnectionTester.java   
public int statusOnException(Connection arg0,Throwable throwable) {
    if (throwable instanceof CommunicationsException
            || "com.MysqL.jdbc.exceptions.jdbc4.CommunicationsException"
                    .equals(throwable.getClass().getName())) {
        return CONNECTION_IS_INVALID;
    }

    if (throwable instanceof sqlException) {
        String sqlState = ((sqlException) throwable).getsqlState();

        if (sqlState != null && sqlState.startsWith("08")) {
            return CONNECTION_IS_INVALID;
        }

        return CONNECTION_IS_OKAY;
    }

    // Runtime/Unchecked?

    return CONNECTION_IS_INVALID;
}
项目:resource_access_tools    文件:AbstractObrDao.java   
/**
 * Executes a given sql query as String using a generic statement. As it returns a ResultSet,* this statement needs to be explicitly closed after the processing of the ResultSet with function
 * {see closeTableStatement()}.
 */
protected ResultSet executesqlQuery(String query) throws sqlException {
    ResultSet rSet;
    try {
        tableStatement = tableConnection.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_READ_ONLY);
        rSet = tableStatement.executeQuery(query);
    } catch (CommunicationsException e) {
        reOpenConnectionIfClosed();
        tableStatement = tableConnection.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_READ_ONLY);
        rSet = tableStatement.executeQuery(query);
    }
    //logger.info("query: " + query);
    return rSet;
}
项目:resource_access_tools    文件:AbstractObrDao.java   
/**
 * Executes the sql query on the given prepared statement. As it returns a ResultSet,* this statement needs to be explicitly closed after the processing of the ResultSet.
 */
protected ResultSet executesqlQuery(PreparedStatement stmt) throws sqlException {
    ResultSet rSet;
    try {
        rSet = stmt.executeQuery();
    } catch (CommunicationsException e) {
        reOpenConnectionIfClosed();
        // Re-calling the execution will generate a MysqLNonTransientConnectionException
        // Those exceptions are catched in each functions to re-execute the query correctly.
        rSet = stmt.executeQuery();
    }
    return rSet;
}
项目:loganalyzer    文件:HConfigure.java   
private void jbtncleandataActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FirsT:event_jbtncleandataActionPerformed
    new Thread() {
        public void run() {
            try {
                Properties config = new Properties();
                config.load(new FileInputStream(System.getProperty("user.dir") + "//config//config.properties"));
                Class.forName(config.getProperty("dbdriver"));
                Connection conn = DriverManager.getConnection(config.getProperty("dbstring"),config.getProperty("dbuser"),config.getProperty("dbpass"));
                int a = JOptionPane.showConfirmDialog(null,"Are you sure to clean data ?","Log Analyzer",JOptionPane.YES_NO_OPTION);
                if (a == JOptionPane.YES_OPTION) {
                    jlblstatus.setText("Cleaning data...");
                    jbtncleandata.setEnabled(false);
                    PreparedStatement ps = conn.prepareStatement("delete from tbl_http_log");
                    int n = ps.executeUpdate();
                    if (n > 0) {
                        JOptionPane.showMessageDialog(null,"Data successfully cleaned",JOptionPane.informatION_MESSAGE);
                        jlblstatus.setText("");
                    }
                }

            } catch (CommunicationsException ce) {
                System.out.println(ce.getMessage());
            } catch (Exception e) {
                System.out.println("Erro - " + e);
            }
        }
    }.start();
}
项目:the-vigilantes    文件:StatementRegressionTest.java   
/**
 * Tests fix for BUG#74998 - readRemainingMultiPackets not computed correctly for rows larger than 16 MB.
 * 
 * This bug is observed only when a multipacket uses packets 127 and 128. It happens due to the transition from positive to negative values in a signed byte
 * numeric value (127 + 1 == -128).
 * 
 * The test case forces a multipacket to use packets 127,128 and 129,where packet 129 is 0-length,this being another boundary case.
 * Query (*1) generates the following MysqL protocol packets from the server:
 * - Packets 1 to 4 contain protocol control data and results Metadata info. (*2)
 * - Packets 5 to 126 contain each row "X". (*3)
 * - Packets 127 to 129 contain row "Y..." as a multipacket (size("Y...") = 32*1024*1024-15 requires 3 packets). (*4)
 * - Packet 130 contains row "Z". (*5)
 * 
 * @throws Exception
 *             if the test fails.
 */
public void testBug74998() throws Exception {
    int maxAllowedPacketAtServer = Integer.parseInt(((MysqLConnection) this.conn).getServerVariable("max_allowed_packet"));
    int maxAllowedPacketMinimumForTest = 32 * 1024 * 1024;
    if (maxAllowedPacketAtServer < maxAllowedPacketMinimumForTest) {
        fail("You need to increase max_allowed_packet to at least " + maxAllowedPacketMinimumForTest + " before running this test!");
    }

    createTable("testBug74998","(id INTEGER NOT NULL AUTO_INCREMENT PRIMARY KEY,data LONGBLOB)"); // (*2)

    StringBuilder query = new StringBuilder("INSERT INTO testBug74998 (data) VALUES ('X')");
    for (int i = 0; i < 121; i++) {
        query.append(",('X')");
    }
    assertEquals(122,this.stmt.executeUpdate(query.toString())); // (*3)

    int lengthOfRowForMultiPacket = maxAllowedPacketMinimumForTest - 15; // 32MB - 15Bytes causes an empty packet at the end of the multipacket sequence

    this.stmt.executeUpdate("INSERT INTO testBug74998 (data) VALUES (REPEAT('Y'," + lengthOfRowForMultiPacket + "))"); // (*4)
    this.stmt.executeUpdate("INSERT INTO testBug74998 (data) VALUES ('Z')"); // (*5)

    try {
        this.rs = this.stmt.executeQuery("SELECT id,data FROM testBug74998 ORDER BY id"); // (*1)
    } catch (CommunicationsException e) {
        if (e.getCause() instanceof IOException && "Packets received out of order".compareto(e.getCause().getMessage()) == 0) {
            fail("Failed to correctly fetch all data from communications layer due to wrong processing of muli-packet number.");
        } else {
            throw e;
        }
    }

    // safety check
    for (int i = 1; i <= 122; i++) {
        assertTrue(this.rs.next());
        assertEquals(i,this.rs.getInt(1));
        assertEquals("X",this.rs.getString(2));
    }
    assertTrue(this.rs.next());
    assertEquals(123,this.rs.getInt(1));
    assertEquals("YYYYY",this.rs.getString(2).substring(0,5));
    assertEquals("YYYYY",this.rs.getString(2).substring(lengthOfRowForMultiPacket - 5));
    assertTrue(this.rs.next());
    assertEquals(124,this.rs.getInt(1));
    assertEquals("Z",this.rs.getString(2));
    assertFalse(this.rs.next());
}
项目:OpenVertretung    文件:StatementRegressionTest.java   
/**
 * Tests fix for BUG#74998 - readRemainingMultiPackets not computed correctly for rows larger than 16 MB.
 * 
 * This bug is observed only when a multipacket uses packets 127 and 128. It happens due to the transition from positive to negative values in a signed byte
 * numeric value (127 + 1 == -128).
 * 
 * The test case forces a multipacket to use packets 127,this.rs.getString(2));
    assertFalse(this.rs.next());
}
项目:ProyectoPacientes    文件:StatementRegressionTest.java   
/**
 * Tests fix for BUG#74998 - readRemainingMultiPackets not computed correctly for rows larger than 16 MB.
 * 
 * This bug is observed only when a multipacket uses packets 127 and 128. It happens due to the transition from positive to negative values in a signed byte
 * numeric value (127 + 1 == -128).
 * 
 * The test case forces a multipacket to use packets 127,this.rs.getString(2));
    assertFalse(this.rs.next());
}
项目:BibliotecaPS    文件:StatementRegressionTest.java   
/**
 * Tests fix for BUG#74998 - readRemainingMultiPackets not computed correctly for rows larger than 16 MB.
 * 
 * This bug is observed only when a multipacket uses packets 127 and 128. It happens due to the transition from positive to negative values in a signed byte
 * numeric value (127 + 1 == -128).
 * 
 * The test case forces a multipacket to use packets 127,this.rs.getString(2));
    assertFalse(this.rs.next());
}
项目:Geometry-wars    文件:StatementRegressionTest.java   
/**
 * Tests fix for BUG#74998 - readRemainingMultiPackets not computed correctly for rows larger than 16 MB.
 * 
 * This bug is observed only when a multipacket uses packets 127 and 128. It happens due to the transition from positive to negative values in a signed byte
 * numeric value (127 + 1 == -128).
 * 
 * The test case forces a multipacket to use packets 127,this.rs.getString(2));
    assertFalse(this.rs.next());
}
项目:TPKB    文件:StatementRegressionTest.java   
/**
 * Tests fix for BUG#74998 - readRemainingMultiPackets not computed correctly for rows larger than 16 MB.
 * 
 * This bug is observed only when a multipacket uses packets 127 and 128. It happens due to the transition from positive to negative values in a signed byte
 * numeric value (127 + 1 == -128).
 * 
 * The test case forces a multipacket to use packets 127,this.rs.getString(2));
    assertFalse(this.rs.next());
}
项目:cloudera-cli-scripts    文件:StatementRegressionTest.java   
/**
 * Tests fix for BUG#74998 - readRemainingMultiPackets not computed correctly for rows larger than 16 MB.
 * 
 * This bug is observed only when a multipacket uses packets 127 and 128. It happens due to the transition from positive to negative values in a signed byte
 * numeric value (127 + 1 == -128).
 * 
 * The test case forces a multipacket to use packets 127,this.rs.getString(2));
    assertFalse(this.rs.next());
}
项目:common-security-module    文件:JDBCHelper.java   
/**
 * This method uses Hibernates SessionFactory to get a Session and using Hibernates Criteria does a sample query
 * to connection and obtain results as part of testing for successful connection.
 *
 * Based on the kind of exceptions this method throws CSException with appropriate message.
 * @param appForm -
 *            The ApplicationForm with application database parameters to
 *            test connection for.
 * @return String - The message indicating that connection and a sql query
 *         was successful
 * @throws CSException -
 *             The exception message indicates which kind of application
 *             database parameters are invalid.
 */
public static String testConnectionHibernate(BaseDBForm appForm) throws CSException {
    ApplicationForm appform = (ApplicationForm) appForm;

    SessionFactory sf = null;
    try {

        Configuration configuration = new Configuration();
        configuration.addResource("gov/nih/nci/security/authorization/domainobjects/Application.hbm.xml");
        configuration.setProperty("hibernate.connection.url",appform.getApplicationDatabaseURL());
        configuration.setProperty("hibernate.connection.username",appform.getApplicationDatabaseUserName());
        configuration.setProperty("hibernate.connection.password",appform.getApplicationDatabasePassword());
        configuration.setProperty("hibernate.dialect",appform.getApplicationDatabaseDialect());
        configuration.setProperty("hibernate.connection.driver_class",appform.getApplicationDatabaseDriver());
        configuration.setProperty("hibernate.connection.pool_size","1");
        sf = configuration.buildSessionFactory();
        Session session = sf.openSession();

        Criteria criteria = session.createCriteria(ApplicationContext.class);
        criteria.add(Expression.eq("applicationName",appform.getApplicationName().trim()));
        criteria.setProjection(Projections.rowCount());

        List results = criteria.list();
        Integer integer = (Integer) results.iterator().next();
        if (integer == null) {
            session.close();
            throw new CSException(displayConstants.APPLICATION_DATABASE_CONNECTION_Failed);
        }

        session.close();
        return displayConstants.APPLICATION_DATABASE_CONNECTION_SUCCESSFUL;

    } catch(Throwable t){
        // Depending on the cause of the exception obtain message and throw a CSException.
        if(t instanceof sqlGrammarException){
            throw new CSException(displayConstants.APPLICATION_DATABASE_CONNECTION_Failed + " "+t.getCause().getMessage());
        }
        if(t instanceof JDBCConnectionException){
            if(t.getCause() instanceof CommunicationsException){
                throw new CSException(displayConstants.APPLICATION_DATABASE_CONNECTION_Failed_URL_SERVER_PORT);
            }
            if(t.getCause() instanceof sqlException){
                throw new CSException(displayConstants.APPLICATION_DATABASE_CONNECTION_Failed_URL);
            }
            throw new CSException(displayConstants.APPLICATION_DATABASE_CONNECTION_Failed+" "+t.getMessage());
        }
        if(t instanceof GenericJDBCException){
            throw new CSException(displayConstants.APPLICATION_DATABASE_CONNECTION_Failed_URL_USER_PASS);
        }
        if(t instanceof HibernateException){
            throw new CSException(displayConstants.APPLICATION_DATABASE_CONNECTION_Failed+" "+t.getMessage());
        }

        throw new CSException(
                displayConstants.APPLICATION_DATABASE_CONNECTION_Failed);
    }

}
项目:common-security-module    文件:JDBCHelper.java   
/**
 * This method uses Hibernates SessionFactory to get a Session and using Hibernates Criteria does a sample query
 * to connection and obtain results as part of testing for successful connection.
 *
 * Based on the kind of exceptions this method throws CSException with appropriate message.
 * @param appForm -
 *            The ApplicationForm with application database parameters to
 *            test connection for.
 * @return String - The message indicating that connection and a sql query
 *         was successful
 * @throws CSException -
 *             The exception message indicates which kind of application
 *             database parameters are invalid.
 */
public static String testConnectionHibernate(Configuration configuration) throws CSException {


    SessionFactory sf = null;
    ResultSet rs = null;
    Statement stmt=null;
    Connection conn = null;
    Session session = null;
    try {
        //System.out.println("testConnectionHibernate*****1");
        sf = configuration.buildSessionFactory();
        //System.out.println("testConnectionHibernate*****2");
        session = sf.openSession();
        //System.out.println("testConnectionHibernate*****3");
        conn = session.connection();
        //System.out.println("testConnectionHibernate*****4");
        stmt = conn.createStatement();
        //System.out.println("testConnectionHibernate*****5");
        stmt.execute("select count(*) from csm_application");
        //System.out.println("testConnectionHibernate*****6");
        rs = stmt.getResultSet();
        //System.out.println("testConnectionHibernate*****7");

        //System.out.println(rs.getMetaData().getColumnCount());

        return displayConstants.APPLICATION_DATABASE_CONNECTION_SUCCESSFUL;

    } catch(Throwable t){
        t.printstacktrace();
        // Depending on the cause of the exception obtain message and throw a CSException.
        if(t instanceof sqlGrammarException){
            throw new CSException(displayConstants.APPLICATION_DATABASE_CONNECTION_Failed+" "+t.getCause().getMessage());
        }
        if(t instanceof JDBCConnectionException){
            if(t.getCause() instanceof CommunicationsException){
                throw new CSException(displayConstants.APPLICATION_DATABASE_CONNECTION_Failed_URL_SERVER_PORT);
            }
            if(t.getCause() instanceof sqlException){
                throw new CSException(displayConstants.APPLICATION_DATABASE_CONNECTION_Failed_URL);
            }
            throw new CSException(displayConstants.APPLICATION_DATABASE_CONNECTION_Failed+" "+t.getMessage());
        }
        if(t instanceof GenericJDBCException){
            throw new CSException(displayConstants.APPLICATION_DATABASE_CONNECTION_Failed_URL_USER_PASS+" ");
        }
        if(t instanceof CacheException){
            throw new CacheException("Please Try Again.\n ");

        }
        if(t instanceof HibernateException){
            throw new CSException(displayConstants.APPLICATION_DATABASE_CONNECTION_Failed+" "+t.getMessage());
        }

        throw new CSException(
                displayConstants.APPLICATION_DATABASE_CONNECTION_Failed_URL_USER_PASS);
    }finally{
        try{
            sf.close();
            rs.close();
            stmt.close();
            conn.close();
            session.close();
        }catch(Exception e){}

    }

}

centos7 设置 mysql 自启动的配置文件中 [Service] User=mysql Group=mysql,user 和 group 这边的 mysql 是指的什么?centos 的登录用户名?

centos7 设置 mysql 自启动的配置文件中 [Service] User=mysql Group=mysql,user 和 group 这边的 mysql 是指的什么?centos 的登录用户名?

centos7 设置 mysql 自启动的配置文件中

[Unit]
Description=MySQL Server
Documentation=man:mysqld(8)
Documentation=http://dev.mysql.com/doc/refman/en/using-systemd.html
After=network.target
After=syslog.target

[Install]
WantedBy=multi-user.target

[Service]
User=mysql
Group=mysql
ExecStart=/usr/local/mysql/bin/mysqld --defaults-file=/etc/my.cnf
LimitNOFILE = 5000
#Restart=on-failure
#RestartPreventExitStatus=1
#PrivateTmp=false

这里的

[Service]

User=mysql

Group=mysql,

user 和 group 这边的 mysql 是指的什么?centos 的登录用户名?还是其他呢?

com.mysql.jdbc.Driver to com.mysql.cj.jdbc.Driver

com.mysql.jdbc.Driver to com.mysql.cj.jdbc.Driver

com.mysql.jdbc.Driver tocom.mysql.cj.jdbc.Driver

MySQL :: MySQL Connector/J 8.0 Developer Guide :: 4.3.1.3 Changes in the Connector/J API https://dev.mysql.com/doc/connector-j/8.0/en/connector-j-api-changes.html

MySQL Connector/J 8.0 Developer Guide  /   ...  /  Changes in the Connector/J API

4.3.1.3 Changes in the Connector/J API

This section describes the changes to the Connector/J API going from version 5.1 to 8.0. You might need to adjust your API calls accordingly:

  • The name of the class that implements java.sql.Driver in MySQL Connector/J has changed from com.mysql.jdbc.Driver tocom.mysql.cj.jdbc.Driver. The old class name has been deprecated.

  • The names of these commonly-used interfaces have also been changed:

    • ExceptionInterceptor: from com.mysql.jdbc.ExceptionInterceptor to com.mysql.cj.exceptions.ExceptionInterceptor

    • StatementInterceptor: from com.mysql.jdbc.StatementInterceptorV2 to com.mysql.cj.interceptors.QueryInterceptor

    • ConnectionLifecycleInterceptor: from com.mysql.jdbc.ConnectionLifecycleInterceptor tocom.mysql.cj.jdbc.interceptors.ConnectionLifecycleInterceptor

    • AuthenticationPlugin: from com.mysql.jdbc.AuthenticationPlugin to com.mysql.cj.protocol.AuthenticationPlugin

    • BalanceStrategy: from com.mysql.jdbc.BalanceStrategy to com.mysql.cj.jdbc.ha.BalanceStrategy.

    •  

     

信息: Loading XML bean definitions from class path resource [Beans.xml]
Loading class `com.mysql.jdbc.Driver''. This is deprecated. The new driver class is `com.mysql.cj.jdbc.Driver''. The driver is automatically registered via the SPI and manual loading of the driver class is generally unnecessary.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd ">

    <bean id="dataSource">
        <property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://rm-2zeo.mysql.rds.aliyuncs.com:3306/vtest"/>
        <property name="username" value="u"/>
        <property name="password" value="I"/>
    </bean>

    <!-- Definition for studentJDBCTemplate bean -->
    <bean id="studentJDBCTemplate">
        <property name="dataSource"  ref="dataSource" />
    </bean>

</beans>

  

 mvn clean;mvn compile;mvn package;mvn install;

mvn 打包jar

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.tutorialspoint</groupId>
    <artifactId>HelloSpringJDBCMysql</artifactId>
    <version>0.0.1-SNAPSHOT</version>

    <dependencies>

        <!-- Spring Core -->
        <!-- http://mvnrepository.com/artifact/org.springframework/spring-core -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>4.1.4.RELEASE</version>
        </dependency>

        <!-- Spring Context -->
        <!-- http://mvnrepository.com/artifact/org.springframework/spring-context -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>4.1.4.RELEASE</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.1.3.RELEASE</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.13</version>
        </dependency>

    </dependencies>
    <build>
        <!--使用的插件列表-->
        <plugins>
            <plugin>
                <artifactId>maven-assembly-plugin</artifactId>
                <version>3.1.0</version>
                <configuration>
                    <descriptorRefs>
                        <descriptorRef>jar-with-dependencies</descriptorRef>
                    </descriptorRefs>
                    <archive>
                        <manifest>
                            <mainClass>com.tutorialspoint.MainApp</mainClass>
                        </manifest>
                    </archive>
                </configuration>
                <executions>
                    <execution>
                        <id>make-assembly</id>
                        <phase>package</phase>
                        <goals>
                            <goal>single</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-jar-plugin</artifactId>
                <configuration>
                    <archive>
                        <manifest>
                            <addClasspath>true</addClasspath>
                            <useUniqueVersions>false</useUniqueVersions>
                            <classpathPrefix>lib/</classpathPrefix>
                            <mainClass>com.tutorialspoint.MainApp</mainClass>
                        </manifest>
                    </archive>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

  

[root@d java]# tree -I target
.
├── pom.xml
├── spring.iml
└── src
├── main
│   ├── java
│   │   └── com
│   │   └── tutorialspoint
│   │   ├── MainApp.java
│   │   ├── StudentDAO.java
│   │   ├── Student.java
│   │   ├── StudentJDBCTemplate.java
│   │   └── StudentMapper.java
│   └── resources
│   └── beans.xml
└── test
└── java

8 directories, 8 files
[root@d java]#

com.tutorialspoint.StudentDAO

package com.tutorialspoint;
import java.util.List;
import javax.sql.DataSource;
public interface StudentDAO {
/**
* This is the method to be used to initialize
* database resources ie. connection.
*/
public void setDataSource(DataSource ds);
/**
* This is the method to be used to create
* a record in the Student table.
*/
public void create(String name, Integer age);
/**
* This is the method to be used to list down
* a record from the Student table corresponding
* to a passed student id.
*/
public Student getStudent(Integer id);
/**
* This is the method to be used to list down
* all the records from the Student table.
*/
public List<Student> listStudents();
/**
* This is the method to be used to delete
* a record from the Student table corresponding
* to a passed student id.
*/
public void delete(Integer id);
/**
* This is the method to be used to update
* a record into the Student table.
*/
public void update(Integer id, Integer age);
}

com.tutorialspoint.Student

package com.tutorialspoint;
public class Student {
/**
CREATE TABLE Student(
ID INT NOT NULL AUTO_INCREMENT,
NAME VARCHAR(20) NOT NULL,
AGE INT NOT NULL,
PRIMARY KEY (ID)
);
* */
private Integer age;
private String name;
private Integer id;
public void setAge(Integer age) {
this.age = age;
}
public Integer getAge() {
return age;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getId() {
return id;
}
}

com.tutorialspoint.StudentMapper

package com.tutorialspoint;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.springframework.jdbc.core.RowMapper;
public class StudentMapper implements RowMapper<Student> {
public Student mapRow(ResultSet rs, int rowNum) throws SQLException {
Student student = new Student();
student.setId(rs.getInt("id"));
student.setName(rs.getString("name"));
student.setAge(rs.getInt("age"));
return student;
}
}

com.tutorialspoint.StudentJDBCTemplate

package com.tutorialspoint;
import java.util.List;
import javax.sql.DataSource;
import org.springframework.jdbc.core.JdbcTemplate;
public class StudentJDBCTemplate implements StudentDAO {
private DataSource dataSource;
private JdbcTemplate jdbcTemplateObject;
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
this.jdbcTemplateObject = new JdbcTemplate(dataSource);
}
public void create(String name, Integer age) {
String SQL = "insert into Student (name, age) values (?, ?)";
jdbcTemplateObject.update( SQL, name, age);
System.out.println("Created Record Name = " + name + " Age = " + age);
return;
}
public Student getStudent(Integer id) {
String SQL = "select * from Student where id = ?";
Student student = jdbcTemplateObject.queryForObject(SQL,
new Object[]{id}, new StudentMapper());
return student;
}
public List<Student> listStudents() {
String SQL = "select * from Student";
List <Student> students = jdbcTemplateObject.query(SQL,
new StudentMapper());
return students;
}
public void delete(Integer id){
String SQL = "delete from Student where id = ?";
jdbcTemplateObject.update(SQL, id);
System.out.println("Deleted Record with ID = " + id );
return;
}
public void update(Integer id, Integer age){
String SQL = "update Student set age = ? where id = ?";
jdbcTemplateObject.update(SQL, age, id);
System.out.println("Updated Record with ID = " + id );
return;
}
}

com.tutorialspoint.MainApp

package com.tutorialspoint;
import java.util.List;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MainApp {
public static void main(String[] args) {
//ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml");
//ApplicationContext context = new ClassPathXmlApplicationContext("/data/gateway/java/src/main/resources/beans.xml");
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
StudentJDBCTemplate studentJDBCTemplate =
(StudentJDBCTemplate)context.getBean("studentJDBCTemplate");
System.out.println("------Records Creation--------" );
studentJDBCTemplate.create("Zara", 11);
studentJDBCTemplate.create("Nuha", 2);
studentJDBCTemplate.create("Ayan", 15);
System.out.println("------Listing Multiple Records--------" );
List<Student> students = studentJDBCTemplate.listStudents();
for (Student record : students) {
System.out.print("ID : " + record.getId() );
System.out.print(", Name : " + record.getName() );
System.out.println(", Age : " + record.getAge());
}
System.out.println("----Updating Record with ID = 2 -----" );
studentJDBCTemplate.update(2, 20);
System.out.println("----Listing Record with ID = 2 -----" );
Student student = studentJDBCTemplate.getStudent(2);
System.out.print("ID : " + student.getId() );
System.out.print(", Name : " + student.getName() );
System.out.println(", Age : " + student.getAge());
}
}

 

 

[root@d java]# java -jar /data/gateway/java/target/HelloSpringJDBCMysql-0.0.1-SNAPSHOT-jar-with-dependencies.jar
Dec 03, 2018 3:11:06 PM org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@133314b: startup date [Mon Dec 03 15:11:06 CST 2018]; root of context hierarchy
Dec 03, 2018 3:11:06 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [beans.xml]
------Records Creation--------
Created Record Name = Zara Age = 11
Created Record Name = Nuha Age = 2
Created Record Name = Ayan Age = 15
------Listing Multiple Records--------
ID : 1, Name : Zara, Age : 11
ID : 2, Name : Nuha, Age : 2
ID : 3, Name : Ayan, Age : 15
----Updating Record with ID = 2 -----
Updated Record with ID = 2
----Listing Record with ID = 2 -----
ID : 2, Name : Nuha, Age : 20
[root@d java]#

  

 

 

 

com.mysql.jdbc.Driver 与 org.gjt.mm.mysql.Driver的区别

com.mysql.jdbc.Driver 与 org.gjt.mm.mysql.Driver的区别

  com.mysql.jdbc.Driver的前身是org.gjt.mm.mysql.Driver,现在主要用com.mysql.jdbc.Driver,但为了保持兼容性保留了org.gjt.mm.mysql.Driver这个路径的引用。

 

mysql-connector-java-5.1.40.jar包结构:

                               

 

com.mysql.jdbc.Driver.java 代码:

package com.mysql.jdbc;

import java.sql.DriverManager;
import java.sql.SQLException;

public class Driver extends NonRegisteringDriver implements java.sql.Driver {
    public Driver() throws SQLException {
    }

    static {
        try {
            DriverManager.registerDriver(new Driver());
        } catch (SQLException var1) {
            throw new RuntimeException("Can''t register driver!");
        }
    }
}

 

org.gjt.mm.mysql.Driver.java 代码:

package org.gjt.mm.mysql;

import java.sql.SQLException;

public class Driver extends com.mysql.jdbc.Driver {
    public Driver() throws SQLException {
    }
}

可以总结出MySQL公司为了保持兼容性让org.gjt.mm.mysql.Driver对com.mysql.jdbc.Driver进行了简单的继承。

 

com.mysql.jdbc.Driver 和 com.mysql.cj.jdbc.Driver 的区别

com.mysql.jdbc.Driver 和 com.mysql.cj.jdbc.Driver 的区别

调试代码时,发现错误:

Loading class `com.mysql.jdbc.Driver''. This is deprecated. The new driver class is `com.mysql.cj.jdbc.Driver''. The driver is automatically registered via the SPI and manual loading of the driver class is generally unnecessary.

在网上巴拉巴拉发现,原来:

com.mysql.jdbc.Driver 是 mysql-connector-java 5 中的;
com.mysql.cj.jdbc.Driver 是 mysql-connector-java 6 中的。

1、JDBC 连接 Mysql5 com.mysql.jdbc.Driver:

spring:
# 数据库连接
datasource:
url: jdbc:mysql://192.168.1.1:3306/demo?useUnicode=true&characterEncoding=utf8&useSSL=false
username: root
password: 123456
driver-class-name: com.mysql.jdbc.Driver

2、JDBC 连接 Mysql6 com.mysql.jdbc.Driver,需要指定时区serverTimezone:

spring:
# 数据库连接
datasource:
url: jdbc:mysql://192.168.1.1:3306/demo?serverTimezone=UTC&useUnicode=true&characterEncoding=utf8&useSSL=false
#    在设定时区的时候,如果设定serverTimezone=UTC,会比中国时间早8个小时,如果在中国,可以选择Asia/Shanghai或者Asia/Hongkong,例如:
#                                           ?serverTimezone=Shanghai&useUnicode=true&characterEncoding=utf8&useSSL=false
username: root
password: 123456
driver-class-name: com.mysql.cj.jdbc.Driver


关于com.mysql.jdbc.CommunicationsException的实例源码的介绍现已完结,谢谢您的耐心阅读,如果想了解更多关于centos7 设置 mysql 自启动的配置文件中 [Service] User=mysql Group=mysql,user 和 group 这边的 mysql 是指的什么?centos 的登录用户名?、com.mysql.jdbc.Driver to com.mysql.cj.jdbc.Driver、com.mysql.jdbc.Driver 与 org.gjt.mm.mysql.Driver的区别、com.mysql.jdbc.Driver 和 com.mysql.cj.jdbc.Driver 的区别的相关知识,请在本站寻找。

本文标签: