我在JDTS驱动程序中使用eclipse。我正在尝试将一行插入到MySQL数据库中。连接和语句生成得很好(我想),但是当我运行executeUpdate方法时,我得到一个空指针异常。
我有一个DBclient类来处理与DB的连接,然后有一个Uploader类来收集所有相关信息并将其提供给我的insert方法。
我的DBclient类:

public class DBclient {

String driver="net.sourceforge.jtds.jdbc";
String URL="xxxx";
String user="xxxx";
String pass="xxxx";
Connection connection;
Statement statement;
ResultSet rs;

public void connect() throws SQLException
{
    try {
        Class.forName(driver);
        }//try
    catch (ClassNotFoundException e)
        {
            e.printStackTrace();
        }//catch

    try {
        connection=DriverManager.getConnection(URL, user, pass);
        statement=connection.createStatement();

        } //try
    catch (SQLException e)
    {
        e.printStackTrace();
    }//catch
}//connect
public void insertToDB(String sqlstatement) throws SQLException
{
    int i=statement.executeUpdate(sqlstatement);
}

}//数据库客户端
然后我的上传类
private String testinsert="insert into xxxx (Latitude, Longitude) values (1, 2)";


public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
     setContentView(R.layout.uploader);
     initialize();
     getaddress();
     update();
     try {
        client.insertToDB(testinsert);
    } catch (SQLException e) {
        // TODO Auto-generated catch block
        Toast t=Toast.makeText(getApplicationContext(), "oops", 4);
        t.show();
    }

   }//onCreate
public void initialize()
{
    client = new DBclient();
    geocoder = new Geocoder(this);
    Bundle coords = getIntent().getExtras();
    street = (TextView) findViewById(R.id.street);
    town = (TextView) findViewById(R.id.town);
    state = (TextView) findViewById(R.id.state);
    country = (TextView) findViewById(R.id.country);
    lat=coords.getDouble("Latitude");
    lon=coords.getDouble("Longitude");

}//initialize
public void update()
{
    street.setText(address.getAddressLine(0));
    town.setText(address.getLocality());
    state.setText(address.getAdminArea());
    country.setText(address.getCountryName());
}//update
public void getaddress()
{
    try
    {
        addresslist = geocoder.getFromLocation(lat, lon, 1);
    } //try
    catch (IOException e)
    {
        Toast t=Toast.makeText(getApplicationContext(), "Input Error", 2);
        t.show();
    }//catch
     address=addresslist.get(0);

}

}//上传程序
空指针异常是从DBclient类的insertToDB()方法引发的。
任何帮助都将不胜感激。

最佳答案

public void insertToDB(String sqlstatement) throws SQLException
{
    int i=statement.executeUpdate(sqlstatement);
}

看起来statement只在connect()类中的DBClient中设置,但在问题中显示的任何其他代码中都不会调用此方法。因此statement将为空,从中调用方法将导致NullPointerException

09-10 09:32
查看更多