我是android新手,为了将android应用程序连接到mysql,我这样做了:
将mysqlconnecter.jar
导入到Android
应用程序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
数据库的方式正确吗?
最佳答案
Android 框架没有内置的 MySQL 连接器,甚至不鼓励使用外部 jar
。实现此目的的最佳方法是通过远程服务器中的 Web 服务,因此您无需将直接 MySQL 查询发送到数据库,而是将 HTTP POST
发送到远程 Web 服务器(例如,编写为PHP、Python 或任何你想要的语言),这将连接到本地数据库并进行查询。
我认为this example可能对你有帮助。
关于android - 将 Android 应用程序连接到 mysql,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22812758/