将Android应用程序连接到mysql

时间:2014-04-02 13:18:00

标签: android mysql

我是android新手,将android应用程序连接到mysql我这样做了:

导入mysqlconnecter.jarAndroid app libs文件夹,然后编写我的代码,如下所示:

import java.sql.*;
public class MainActivity extends Activity {

    private EditText  username=null;
    private EditText  password=null;
    private TextView attempts;
    private Button login;
    int counter = 3;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        username = (EditText)findViewById(R.id.editText1);
        password = (EditText)findViewById(R.id.editText2);
        attempts = (TextView)findViewById(R.id.textView3);
        attempts.setText(Integer.toString(counter));
        login = (Button)findViewById(R.id.button1);
    }

    public void login(View view) throws ClassNotFoundException{
        Connection conn=null;
        ResultSet rs=null;
        PreparedStatement  stmt=null;
        String username1 = String.valueOf(username.getText());
        String password1 =  String.valueOf(password.getText());
        String Query="SELECT * from users where mail=? and password=?";
        try{
            Class.forName("com.mysql.jdbc.Driver");
            conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/wst","xxxxxxxx","xxxxxx");

            stmt=conn.prepareStatement(Query);
            stmt.setString(1, username1);
            stmt.setString(2, password1);
            rs=stmt.executeQuery();
            boolean more=rs.next();

            if(more){
                Toast.makeText(getApplicationContext(), "Redirecting...",
                        Toast.LENGTH_SHORT).show();
            }
            else{
                Toast.makeText(getApplicationContext(), "Wrong Credentials",
                        Toast.LENGTH_SHORT).show();
                attempts.setBackgroundColor(Color.RED);
                counter--;
                attempts.setText(Integer.toString(counter));
                if(counter==0){
                    login.setEnabled(false);
                }

            }

        }

        catch(SQLException e){

        }



    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

}

连接MySQL数据库是否正确?

1 个答案:

答案 0 :(得分:2)

Android框架没有内置的MySQL连接器,因此不建议使用外部jar。您可以通过远程服务器中的Web服务实现此目的的最佳方式,因此您不必将直接MySQL查询发送到数据库,而是将HTTP POST发送到远程Web服务器(例如,用PHP编写) ,Python或任何你想要的东西),这将连接到本地数据库并进行查询。

我认为this example可能对您有帮助。