2014-04-02 64 views
0

我是新來的機器人,與Android應用連接到MySQL我這樣做:連接Android應用到mysql

進口mysqlconnecter.jarAndroid應用程序庫文件夾,然後寫我的代碼如下圖所示:

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數據庫是否正確?

+0

你在你的android設備('localhost')上運行mysql數據庫嗎? – Fortega

回答

2

對於Android框架沒有內置的MySQL連接器,因此不鼓勵使用外部的jar。您可以通過遠程服務器中的web服務完成此操作,因此您不需要將直接MySQL查詢發送到數據庫,而是將HTTP POST發送到遠程Web服務器(例如,使用PHP,Python或任何您想要的),這將連接到本地數據庫並進行查詢。

我認爲this example可能會幫助你。