有时与Android的JDBC连接不起作用

时间:2015-07-10 10:55:42

标签: java android mysql jdbc google-cloud-sql

几天前我开始开发一个Android应用程序,我决定使用 JDBC 进行数据库连接(数据库在云端),我知道使用php webservice更安全。这是我的问题:

直到昨天我能够建立连接并获取查询结果并登录到应用程序,但不知何故我现在无法做到。我正在为我的数据库使用 Google Cloud Sql ,一切都很好,我可以通过 Mysql Workbench 连接到我的数据库并执行相同的查询。

有趣的是,当我尝试使用错误的密码登录应用程序时,我得到登录失败错误,这意味着我从db获得结果但是使用正确的密码我什么都没有,这很奇怪。

谁能猜到可能出错的地方?

这是我的数据库连接类

public class DBTransactions {  
// JDBC driver name and database URL
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://***:3306/";

//  Database credentials
static final String DB_Name = "dbname";
static final String USER = "user";
static final String PASS = "pass";

public static Nurse NurseLogin(String username, String pass) {
    Connection conn = null;
    Statement stmt = null;
    Nurse nurse= new Nurse();
    try {//STEP 2: Register JDBC driver
        Class.forName("com.mysql.jdbc.Driver");

        //STEP 3: Open a connection
        System.out.println("Connecting to database...");
        conn = DriverManager.getConnection(DB_URL + DB_Name, USER, PASS);

        //STEP 4: Execute a query
        System.out.println("Creating statement...");
        stmt = conn.createStatement();
        String sql;
        sql = "SELECT * FROM falldb.nurse WHERE username='" + username + "' AND pass='" + pass + "'";
        ResultSet rs = stmt.executeQuery(sql);
        System.out.println("Query!!");

        //STEP 5: Extract data from result set
        while (rs.next()) {
            System.out.println("Data exist!!");
            //Retrieve by column name
            nurse.setID(rs.getInt("idNurse"));
            nurse.setName(rs.getString("name"));
            nurse.setSurname(rs.getString("surname"));
            nurse.setUsername(rs.getString("username"));
            nurse.setPass(rs.getString("pass"));

            //Display values
            System.out.print("ID: " + nurse.getID());
            System.out.print(", First: " + nurse.getName());
            System.out.println(", Last: " + nurse.getSurname());
            System.out.println("Finished!!");
        }
        //STEP 6: Clean-up environment
        rs.close();
        stmt.close();
        conn.close();
    } catch (SQLException se) {//Handle errors for JDBC
        se.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        //finally block used to close resources
        try {
            if (stmt != null)
                stmt.close();
        } catch (SQLException se2) {
        }
        try {
            if (conn != null)
                conn.close();
        } catch (SQLException se) {
            se.printStackTrace();
        }//end finally try
    }//end try
    return nurse;
 }
}

这是Login.class,我调用DBTransactions.NurseLogin

public class Login extends Activity {

Button btnLogin;
EditText etUser;
EditText etPass;
TextView tvResult;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login);

    btnLogin = (Button) findViewById(R.id.btnLogin);
    btnLogin.setOnClickListener(clickLogin);

    etUser = (EditText) findViewById(R.id.etUser);
    etPass = (EditText) findViewById(R.id.etPass);
    tvResult = (TextView) findViewById(R.id.tvResult);
}
public View.OnClickListener clickLogin = new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        final String u = etUser.getText().toString();
        final String p = etPass.getText().toString();

        new AsyncTask() {
            @Override
            protected Object doInBackground(Object[] params) {
                return DBTransactions.NurseLogin(u, p);
            }
            @Override
            protected void onPostExecute(Object o) {

                Nurse nurse = (Nurse) o;
                if (nurse.getName() != null) {
                    tvResult.setText("Welcome " + nurse.getName().toUpperCase());

                    Intent i = new Intent(Login.this, PatientOperations.class);
                    i.putExtra("objects.Nurse", nurse);
                    startActivity(i);
                } else {
                    tvResult.setText("Login Failed");
                }
            }
        }.execute();
    }
 };
}

1 个答案:

答案 0 :(得分:0)

经过几天的尝试和失败后,我终于找到了导致问题的原因。似乎在使用 SELECT * 从db中选择所有列时,一切正常。但是当试图使用 WHERE 子句时出错了。

这有效

NSURL *fileURL =[[NSURL alloc] initFileURLWithPath:SVGpath];
NSURLRequest*req =[NSURLRequest requestWithURL:fileURL];
[webView setScalesPageToFit:YES];
[webView loadRequest:req];

//uncheck opaque property of UIWebView.

这不是

sql = "SELECT * FROM falldb.nurse";

解决方案是在使用 WHERE 子句而不是使用*时使用列的确切名称。我把我的代码更改为:

sql = "SELECT * FROM falldb.nurse WHERE username='" + username + "' AND pass='" + pass + "'";

现在我得到了结果。