简体   繁体   English

我在连接建立中得到空指针异常

[英]I am getting null pointer exception in connection establishment

Here I am using jdbcHelper to establish connection with database but some times(not all the times) I am getting exception as null pointer in connection establishment but that is not all the time. 这里我使用jdbcHelper建立与数据库的连接,但有时(并非所有时间)我在连接建立中获得异常作为空指针,但这不是所有的时间。 here is my code.This code is used to insert data into database.. 这是我的代码。这段代码用于将数据插入数据库..

 Connection conn = JDBCHelper.getConnection();
        PreparedStatement ps1 = null;
        System.out.println("In Side DATA BASE");
        System.out.println("in side database deviceid=" + s);
        System.out.println("in side database rfide=" + s1);
        System.out.println("in side database longitude=" + lati);
        System.out.println("in side database latitude= " + lot);
        System.out.println("in side database datalength=" + data_length);
        Date date = new Date();
        java.sql.Timestamp dt = new java.sql.Timestamp(date.getTime());
        int flag = 1;
        System.out.println("date=" + dt);
        System.out.println("flag=" + flag);
        try {
            String hql = "insert into gpsData1(dateTime,deviceid,latitude,longitude,rfid,flag,datalength) values(?,?,?,?,?,?,?)";
            ps1 = conn.prepareStatement(hql);
            ps1.setString(1, dt.toString());
            ps1.setString(2, s);
            ps1.setFloat(3, lati);
            ps1.setFloat(4, lot);
            ps1.setString(5, s1);
            ps1.setInt(6, flag);
            ps1.setInt(7, data_length);
            ps1.executeUpdate();
            conn.commit();
            System.out.println("DATA BASE Inserting Completed");
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            JDBCHelper.close(ps1);
            JDBCHelper.close(conn);
        }

This is my JDBC code.. 这是我的JDBC代码..

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class JDBCHelper {

    public static final String url = "jdbc:mysql://localhost:3306/treamisdemo";
    public static final String uid = "root";
    public static final String pwd = "myserver";

    /**
     * @param
     * args
     */
    static {
        try {
            Class.forName("com.mysql.jdbc.Driver");
            System.out.println("connection is sucessful");
        } catch (ClassNotFoundException e) {
            System.err.println("ERROR: failed to load mysql JDBC driver.");
            e.printStackTrace();
        }
    }

    public static void close(ResultSet c) {
        try {
            if (c != null) {
                c.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public static void close(Statement c) {
        try {
            if (c != null) {
                c.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public static void close(Connection c) {
        try {
            if (c != null) {
                c.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public static Connection getConnection() {
        Connection con = null;
        try {
            con = DriverManager.getConnection(url, uid, pwd);
            System.out.println("obtain connection =" + con);
            con.setAutoCommit(false);
            return con;
        } catch (SQLException e) {
            e.printStackTrace();
            return null;
        }


    }
}

This is the stack trace.. 这是堆栈跟踪..

com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: Data sourc
e rejected establishment of connection,  message from server: "Too many connecti
ons"
        at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)

        at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstruct
orAccessorImpl.java:57)
        at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingC
onstructorAccessorImpl.java:45)
        at java.lang.reflect.Constructor.newInstance(Constructor.java:526)
        at com.mysql.jdbc.Util.handleNewInstance(Util.java:411)
        at com.mysql.jdbc.Util.getInstance(Util.java:386)
        at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1013)
        at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:987)
        at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:982)
        at com.mysql.jdbc.MysqlIO.doHandshake(MysqlIO.java:1128)
        at com.mysql.jdbc.ConnectionImpl.coreConnect(ConnectionImpl.java:2336)
        at com.mysql.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:2
369)
        at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2153)
        at com.mysql.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:792)
        at com.mysql.jdbc.JDBC4Connection.<init>(JDBC4Connection.java:47)
        at sun.reflect.GeneratedConstructorAccessor39.newInstance(Unknown Source
)
        at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingC
onstructorAccessorImpl.java:45)
        at java.lang.reflect.Constructor.newInstance(Constructor.java:526)
        at com.mysql.jdbc.Util.handleNewInstance(Util.java:411)
        at com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:381)
        at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java
:305)
        at java.sql.DriverManager.getConnection(DriverManager.java:571)
        at java.sql.DriverManager.getConnection(DriverManager.java:215)
        at com.treamis.transport.vehicle.JDBCHelper.getConnection(JDBCHelper.jav
a:71)
        at com.treamis.transport.vehicle.MyTimerTask.getRoutePointList(MyTimerTa
sk.java:639)
        at com.treamis.transport.vehicle.MyTimerTask.sendSms(MyTimerTask.java:10
8)
        at com.treamis.transport.vehicle.MyTimerTask.run(MyTimerTask.java:71)
        at java.util.TimerThread.mainLoop(Timer.java:555)
        at java.util.TimerThread.run(Timer.java:505)

The exception states: "Too many connections" 例外情况: "Too many connections"

You must close every connection after you finished using it. 完成使用后,必须关闭每个连接。

Sometimes you don't close the connection you open. 有时您不会关闭打开的连接。 You should move getConnection call inside the try block so you will always close if in finally statement. 您应该在try块中移动getConnection调用,这样如果在finally语句中,您将始终关闭。

Another possible reason is that you try to connect too many times simultaneously. 另一个可能的原因是您尝试同时连接太多次。

Suggestions: 建议:

  1. The connection should be opened only when needed. 只有在需要时才应打开连接。 No need to open it immediately at the beginning of the function. 无需在功能开始时立即打开它。
  2. The NPE you get is because getConnection() returns null on error. 你得到的NPE是因为getConnection()在出错时返回null。 I think it is better to throw an exception in this case rather than return null. 我认为最好在这种情况下抛出异常而不是返回null。
  3. If you use Java 7, you can use try-with-resources to close resources after finished using them. 如果使用Java 7,则可以在完成使用后使用try-with-resources关闭资源。
  4. Make sure you use reasonable amount of DB connections. 确保使用合理数量的数据库连接。 If you need more than available connection, consider using one connection for all your DB accesses. 如果您需要的连接多于可用连接,请考虑为所有数据库访问使用一个连接。

You can use a single connection for this Timer task. 您可以为此Timer任务使用单个连接。 Commit on sucessful update but dont close the connection, reuse it. 提交成功更新但不要关闭连接,重用它。

Something like this: 像这样的东西:

boolean doInsert(){
  // your insert code
  // String hql = "insert into gpsData1(dateTime,deviceid,latitude,longitude,rfid
   return ps1.executeUpdate(); // this returns true or false
}


boolean isInsert = doInsert();
if(isInsert){
   conn.commit();
}   

使用像HikariCPBoneCP这样的真实连接池。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM