使用JDBC" java.lang.NullPointerException"时出错

时间:2015-08-23 23:40:16

标签: java android sql-server jdbc

我收到错误

  

java.lang.NullPointerException:尝试调用接口方法   ' java.sql.Statement java.sql.Connection.createStatement()'在null   对象参考   com.example.jacquesarroyo.onlinelibrary.suggestions $ 3.onClick(suggestions.java:81)

这是我使用的代码:

add = (Button) findViewById(R.id.btnadd);
errorlbl = (TextView) findViewById(R.id.lblerror);
title = (EditText) findViewById(R.id.txttitle);
author = (EditText) findViewById(R.id.txtauthor);
year = (EditText) findViewById(R.id.txtyear);
location = (EditText) findViewById(R.id.txtlocation);

ipaddress = "10.0.0.5";   
db = "SampleDatabase"; 
username = "admin"
password = "admin";
connect = ConnectionHelper(username, password, db, ipaddress);

add.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            try {
                st = connect.createStatement();
                preparedStatement = connect
                        .prepareStatement("Insert into Books(Title,Author,Year) values ('"
                                + title.getText().toString()
                                + "','"
                                + author.getText().toString()
                                + "','"
                                + year.getText().toString() + "')");
                preparedStatement.executeUpdate();
                errorlbl.setText("Data Added successfully");
            } catch (SQLException e) {
                errorlbl.setText(e.getMessage().toString());
            }
        }
    });

@SuppressLint("NewApi")
private Connection ConnectionHelper(String user, String password,
                                    String database, String server) {
    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
            .permitAll().build();
    StrictMode.setThreadPolicy(policy);
    Connection connection = null;
    String ConnectionURL = null;
    try {
        Class.forName("net.sourceforge.jtds.jdbc.Driver");
        ConnectionURL = "jdbc:jtds:sqlserver://" + server + ";"
                + "databaseName=" + database + ";user=" + user
                + ";password=" + password + ";" + "ssl=false";
        connection = DriverManager.getConnection(ConnectionURL);


    } catch (SQLException se) {
        Log.e("ERROR", se.getMessage());
    } catch (ClassNotFoundException e) {
        Log.e("ERROR", e.getMessage());
    } catch (Exception e) {
        Log.e("ERROR", e.getMessage());
    }
    return connection;
}

第81行是:st = connect.createStatement();

1 个答案:

答案 0 :(得分:1)

NullPointerException表示您尝试使用的变量未初始化或为null

致电之前:

connect.createStatement();

您必须先通过以下方式初始化connect对象:

Connection connect = ConnectionHelper(user,password,database,server);

请记住变量的范围。