无法从JDBC获得连接

时间:2016-07-18 05:38:08

标签: java android jdbc

我在Android Studio上有这个课程:

@SuppressLint("NewAPI")
public void Connect() throws Exception {
    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
    StrictMode.setThreadPolicy(policy);
    connection = null;
    String S_url = null;
    String driver = null;
    try {
        driver = "net.sourceforge.jtds.jdbc.Driver";
        Class.forName(driver);
        S_url = "jdbc:jtds:sqlserver://" + ip + ";"
                + "databaseName=" + db + ";user=" + un + ";password="
                + pass + ";";
        connection = DriverManager.getConnection(S_url);
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    } catch (SQLException e) {
        e.printStackTrace();
    }
}
public Connection getConnection() {
    return connection;
}

用于连接我的sql server数据库。这是一个问题,我无法从此类获得用于PreparedStatement的连接,尽管我可以连接到我的数据库。

我在Eclipse上尝试了这个代码并且运行得很好:

我的朋友在他的Android Studio上运行这个项目,它也有效。

编辑:

这是一个例子:

public class Account_Control {
Connection connect;

// CONNECT DATABASE
public Account_Control(Connection connection) {
    this.connect = connection;
}


public boolean CheckUsername(String username) throws Exception {
    try {
        PreparedStatement query = connect.prepareStatement("select Username from Account where Username = '" + username + "'");
        ResultSet rs = query.executeQuery();

当我在MainActivity上调用此类时

private DatabaseConnection db;
private Account_Control account_control;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    getSupportActionBar().hide();
    setContentView(R.layout.activity_login);
    db = new DatabaseConnection();
    try {
        db.Connect();
    } catch (Exception e) {
        e.printStackTrace();
    }
    account_control = new Account_Control(db.getConnection());

db.getConnection()无效,它返回null account_control

堆栈跟踪:

java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.haitr.planed_12062016/com.example.haitr.planed_12062016.LoginActivity}: 
java.lang.NullPointerException: Attempt to invoke interface method 'java.sql.PreparedStatement java.sql.Connection.prepareStatement(java.lang.String)' on a null object reference

0 个答案:

没有答案