public class MainActivity extends AppCompatActivity { private EditText userName; private EditText password; private Button loginBtn; private Connection connection; private String url = "jdbc:mysql://localhost:3306/userinfo?useUnicode=true&characterEncoding=utf8&autoReconnect=true&failOverReadOnly=false&maxReconnects=10"; private String user = "root"; private String pass = "password"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); userName = findViewById(R.id.etUserName); password = findViewById(R.id.etPassword); loginBtn = findViewById(R.id.btnLogin); loginBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String userNameStr = userName.getText().toString(); String passwordStr = password.getText().toString(); try { Class.forName("com.mysql.jdbc.Driver"); connection = DriverManager.getConnection(url, user, pass); String sql = "select * from user where userName = ? and password = ?"; PreparedStatement preparedStatement = connection.prepareStatement(sql); preparedStatement.setString(1, userNameStr); preparedStatement.setString(2, passwordStr); ResultSet resultSet = preparedStatement.executeQuery(); if (resultSet.next()) { Intent intent = new Intent(MainActivity.this, HomePageActivity.class); startActivity(intent); } else { Toast.makeText(MainActivity.this, "登录失败,请重试", Toast.LENGTH_SHORT).show(); } } catch (ClassNotFoundException | SQLException e) { e.printStackTrace(); } finally { try { connection.close(); } catch (SQLException e) { e.printStackTrace(); } } } }); } }
上面的代码是一个简单的Android App中使用MySQL数据库的示例。在代码中,大家首先定义了数据库连接的url、用户名和密码,然后在登录按钮的点击事件中建立了与数据库的连接。在进行查询操作时,大家使用了预处理语句来防止SQL注入攻击。最后,在操作完成后要记得关闭连接。
MySQL数据库和App的连接可以帮助开发者实现数据的快速读写和查询,提高App的效率和用户体验。当然,在使用这种方式连接数据库时,需要注意数据安全和防止SQL注入攻击等问题。