The most spread method to connect to a remote MySQL database from an android device, is to put some kind of service into the middle. Since MySQL is usually used together with PHP, the easiest and most obvious way to write a PHP script to manage the database and run this script using HTTP protocol from the android system. |
|
We can code the data in JSON format, between Android and PHP with the easy to use built in JSON functions in both languages.
I present some sample code, which selects data from a database depending on a given condition and creates a log message on the android side with the received data.
Lets suppose that we have a MySQL database named PeopleData, and a table int created, with the following SQL:
-
CREATE TABLE `people` (
-
`id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
-
`name` VARCHAR( 100 ) NOT NULL ,
-
`sex` BOOL NOT NULL DEFAULT '1',
-
`birthyear` INT NOT NULL
-
)
We want to get all the data of the people, who were born after a specified year.
The PHP code will be very simple:
- connect to the database
- run an SQL query, with a WHERE block depending on data from POST/GET values
- output it in JSON format
For example we will have this functionality in the getAllPeopleBornAfter.php file:
-
<?php
-
mysql_connect("host","username","password");
-
mysql_select_db("PeopleData");
-
-
$q=mysql_query("SELECT * FROM people WHERE birthyear>'".$_REQUEST['year']."'");
-
while($e=mysql_fetch_assoc($q))
-
$output[]=$e;
-
-
print(json_encode($output));
-
-
mysql_close();
-
?>
The Android part is only a bit more complicated:
-use a HttpPost to get the data, sending the year value
-convert response to string
-parse JSON data, and use it as you want
-
-
//the year data to send
-
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
-
nameValuePairs.add(new BasicNameValuePair("year","1980"));
-
-
//http post
-
try{
-
HttpClient httpclient = new DefaultHttpClient();
-
HttpPost httppost = new HttpPost("http://example.com/getAllPeopleBornAfter.php");
-
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
-
HttpResponse response = httpclient.execute(httppost);
-
HttpEntity entity = response.getEntity();
-
-
-
Log.e("log_tag", "Error in http connection "+e.toString());
-
}
-
//convert response to string
-
try{
-
-
StringBuilder sb = new StringBuilder();
-
-
while ((line = reader.readLine()) != null) {
-
sb.append(line + "\n");
-
}
-
is.close();
-
-
result=sb.toString();
-
-
Log.e("log_tag", "Error converting result "+e.toString());
-
}
-
-
//parse json data
-
try{
-
JSONArray jArray = new JSONArray(result);
-
for(int i=0;i<jArray.length();i++){
-
JSONObject json_data = jArray.getJSONObject(i);
-
Log.i("log_tag","id: "+json_data.getInt("id")+
-
", name: "+json_data.getString("name")+
-
", sex: "+json_data.getInt("sex")+
-
", birthyear: "+json_data.getInt("birthyear")
-
);
-
}
-
}
-
}catch(JSONException e){
-
Log.e("log_tag", "Error parsing data "+e.toString());
-
}
Of course it is possible to use HTTPS and send password to access data, or do more complex data processing on either side, or write more general code, which
does not include this much predefined parameters in the database accessing query.
<!-- google_ad_section_end -->
分享到:
相关推荐
在"VC connecting to MYSQL.doc"文档中,可能包含了更多关于如何在VC++中配置MySQL Connector/C++,如何处理连接错误,以及如何使用C API进行更复杂数据库操作的详细步骤和示例代码。确保仔细阅读并理解这些内容,...
System.err.println("Error connecting to the database: " + e.getMessage()); } } } ``` 确保在项目中添加了对应的数据库驱动库,例如,对于MySQL,需要添加MySQL Connector/J的JAR文件到类路径中。 最后,...
System.err.println("Error connecting to the database: " + e.getMessage()); } } } ``` 这里,`url`是数据库服务器的地址,包括端口号(默认3306)和要连接的数据库名。`username`和`password`是你的MySQL...
Debug.LogError("Error connecting to MySQL: " + ex.Message); } } ``` **步骤四:执行SQL命令** 现在你可以使用这个连接执行SQL查询、插入、更新和删除操作。例如,执行一个简单的SELECT查询: ```csharp ...
System.err.println("Error connecting to database: " + e.getMessage()); } } } ``` 这段代码首先加载了MySQL JDBC驱动,然后使用`DriverManager.getConnection()`方法建立到数据库的连接。注意,URL中包含...
Debug.LogError("Error connecting to MySQL: " + ex.Message); } finally { if (conn != null && conn.State == ConnectionState.Open) { conn.Close(); } } } ``` 在这个例子中,`connStr`是包含数据库连接...
System.err.println("Error connecting to the database: " + e.getMessage()); } } } ``` 在这个例子中,`DriverManager.getConnection()`方法用于建立与MySQL服务器的连接。URL指定数据库的位置,包括主机名、...
在MySQL服务器的运行过程中,可能会遇到“ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/tmp/mysql.sock'”这样的错误。这个错误提示表明,客户端试图通过Unix域套接字(socket文件)...
System.err.println("Error connecting to the database: " + e.getMessage()); } } } ``` 在这个例子中,我们首先导入了必要的`java.sql`包,然后通过`DriverManager.getConnection()`方法建立到数据库的连接。...
System.out.println("Error connecting to the database."); e.printStackTrace(); } } } ``` 在这个例子中,`Class.forName("com.mysql.jdbc.Driver")`是用来加载MySQL的JDBC驱动,`DriverManager.get...
qDebug() << "Error connecting to database:" ().text(); } ``` 6. **编译并运行**: - 编译并运行你的应用程序,如果一切配置正确,你应该能够成功连接到MySQL服务器并执行查询。 以上就是QT 5.15.2中安装和...
kettle连接Oracle报错kettle连接Oracle报错报错信息 kettle连接Oracle报错 ...Error connecting to database: (using class oracle.jdbc.driver.OracleDriver) Listener refused the connection with th
System.out.println("Error connecting to the database."); e.printStackTrace(); } } } ``` 在上述代码中,我们首先通过`Class.forName()`加载MySQL的JDBC驱动,然后使用`DriverManager.getConnection()`方法...
System.err.println("Error connecting to the database: " + e.getMessage()); } } } ``` 总的来说,mysql-connector-java-8.0.23.jar是Java开发者不可或缺的工具,它为与MySQL数据库的交互提供了便利和强大的...
System.out.println("Error connecting to the database."); e.printStackTrace(); } } } ``` 在上述代码中,`Class.forName()`方法用于加载驱动,`DriverManager.getConnection()`方法用于建立与数据库的连接...
System.err.println("Error connecting to the database: " + e.getMessage()); } } } ``` 在这个例子中,我们使用`DriverManager.getConnection()`方法来建立到MySQL服务器的连接。`url`参数应包含数据库的地址...
System.err.println("Error connecting to the database: " + e.getMessage()); } } } ``` 在上述代码中,`DriverManager.getConnection()`方法用于建立连接,参数分别是数据库URL、用户名和密码。 5. **处理...
System.err.println("Error connecting to the database: " + e.getMessage()); } } } ``` 在上述代码中,`DriverManager.getConnection()`方法用于建立连接,URL指定数据库的地址(包括主机名、端口和数据库名)...