Android mysql查询数据库
时间: 2023-11-02 21:09:48 浏览: 43
可以使用Java提供的JDBC API连接MySQL数据库,并使用SQL语句查询数据。以下是一个简单的示例:
```java
import java.sql.*;
public class MySQLExample {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/mydatabase";
String user = "myusername";
String password = "mypassword";
try {
// Register the JDBC driver
Class.forName("com.mysql.jdbc.Driver");
// Create a connection
Connection conn = DriverManager.getConnection(url, user, password);
// Create a statement
Statement stmt = conn.createStatement();
// Execute the query
ResultSet rs = stmt.executeQuery("SELECT * FROM mytable");
// Process the results
while (rs.next()) {
String name = rs.getString("name");
int age = rs.getInt("age");
System.out.println("Name: " + name + ", Age: " + age);
}
// Close the resources
rs.close();
stmt.close();
conn.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
```
在此示例中,我们使用了MySQL的JDBC驱动程序,并使用了一个SELECT * FROM mytable查询来检索一个名为mytable的表中的所有行。然后,我们遍历结果集并打印每行中的name和age字段。最后,我们关闭资源以释放内存并避免潜在的泄漏。