Android + mysql:连接类返回Null对象

时间:2018-08-23 11:32:24

标签: android mysql jdbc jtds

我正在尝试通过jtds jdbc将android登录应用程序连接到XAMP服务器(本地计算机上正在运行Apache)。似乎代码无法连接服务器。这是代码:

ConnectionClass.java

package com.ercess.databaseconnection;

import android.annotation.SuppressLint;
import android.os.StrictMode;
import android.os.Bundle;
import android.util.Log;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class ConnectionClass {

    public String driver = "net.sourceforge.jtds.jdbc.Driver";

    String url = "jdbc:mysql://localhost/events-test";
    //String url = "jdbc:mysql://127.0.0.1/events-test";
    public String un = "root";
    public String password = "password";
    public String db = "users";

    @SuppressLint("NewApi")
    public Connection CONN() {
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);
        java.sql.Connection conn = null;
        String ConnURL = null;
        try{
            Class.forName(driver);
            ConnURL = "jdbc:jtds:sqlserver://" + "127.0.0.1" +";databaseName="+ db + ";user=" + un+ ";password=" + password + ";";

            conn = DriverManager.getConnection(ConnURL);



        }catch (SQLException se){
            Log.e("ERROR", se.getMessage());
        }catch (ClassNotFoundException e){
            Log.e("ERROR", e.getMessage());
        }catch(Exception e){
            Log.e("ERROR", e.getMessage());
        }
        //Log.d("conn",conn.toString());
        return conn;
    }
}

MainActivity.java

    package com.ercess.databaseconnection;

    import android.app.ProgressDialog;
    import android.os.AsyncTask;
    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    import android.view.View;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.Toast;
    import java.sql.Connection;
    import java.sql.Statement;
    import java.sql.ResultSet;
    public class MainActivity extends AppCompatActivity {
        EditText email, password;
        Button login;
        ProgressDialog progressDialog;
        ConnectionClass connectionClass;
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            email = findViewById(R.id.email);
            password = findViewById(R.id.password);
            login = findViewById(R.id.login);
            connectionClass = new ConnectionClass();
            progressDialog = new ProgressDialog(this);
            login.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Dologin dologin = new Dologin();
                    dologin.execute();
                }
            });
        }
        public class Dologin extends AsyncTask<String, String, String>{
            String emailstring = email.getText().toString();
            String passstring = password.getText().toString();
            String z = "";
            boolean isSuccess = false;
            String em, pass;
            @Override
            protected void onPreExecute() {
                progressDialog.setMessage("Loading...");
                progressDialog.show();
                super.onPreExecute();
            }
            protected String doInBackground(String... params){
                if(emailstring.trim().equals("") || passstring.trim().equals(""))
                    z = "Please enter all fields........";
                else
                {
                    try{
                        Connection con = connectionClass.CONN();
                        if(con == null){
                            z="Please, check your internet connection....";
                        }else{
                            String query = "select * from users where user='"+emailstring+"'and password='"+passstring+"'";
                            Statement stmt = con.createStatement();
                            ResultSet rs = stmt.executeQuery(query);
                            while(rs.next())
                            {
                                em = rs.getString(0);

                                pass = rs.getString(1);

                                if(em.equals(emailstring) && pass.equals(passstring))
                                {
                                    isSuccess = true;
                                    z = "Login successful...";
                                }
                                else isSuccess = false;
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        isSuccess = false;
                        z = "Exceptions"+ex;
                    }
                }
                return z;
            }
            @Override
            protected void onPostExecute (String s){
                Toast.makeText(getBaseContext(),""+z, Toast.LENGTH_LONG).show();
                progressDialog.hide();
            }
        }
}  

我得到以下输出:“请检查您的互联网连接...。”

仅当con = null时,此消息才应触发。 如何解决?

2 个答案:

答案 0 :(得分:2)

Android不支持MySQL或SQL Server:- 您可以使用Sqllite https://www.tutorialspoint.com/android/android_sqlite_database.htm 或者您可以通过PHP访问MySQL:- https://www.tutorialspoint.com/android/android_php_mysql.htm

答案 1 :(得分:0)

我遇到了同样的问题... 主要问题在于您的ConnectionClass。

String url = "jdbc:mysql://localhost/events-test";
    public String un = "root";
    public String password = "password";
    public String db = "users";

这是您的代码,那么,当您使用root和localhost时,它正在检查您的Internet连接问题。因此,要解决此问题,您必须创建一个新用户,而不是localhost,请使用Internet的IP地址。

  1. 要创建新用户,如果您使用的是phpmyadmin,请单击“特权”选项卡,在其中看到“添加用户”选项。在此处创建用户,将所有数据库特权授予该用户并保存。然后使用用户名和密码代替“ root”和“ password”。

  2. 现在要获取您的IP地址,请转到命令提示符,键入ipconfig,您将找到ip地址。在上面的代码中,而不是localhost,键入您的IP地址,例如,

    字符串url =“ jdbc:mysql://192.168.0.12/events-test”;

  3. 并且您必须在AndroidManifest.xml中提供互联网访问权限

    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
    

这应该可以解决您的问题。