In Android development, most of the ways to connect to a remote MySQL database are by adding a specific service into the code. Since MySQL is usually used in conjunction with PHP, the simplest and most common method is to write PHP scripts to manage data connections and to run the script from the Android system using the HTTP protocol .
Data can be written in JSON format , and both languages are easily embedded in JSON functions between Android and PHP.
I demonstrate the sample code that reads data from a database based on a given condition and creates a log message on the Android development platform to receive data.
Let's say we have a MySQL database named peopledata , and we created a data table using the following SQL statement:
[Java]View PlainCopy
- CREATE TABLE ' People ' (' ID ' INT NOT NULL auto_increment PRIMARY KEY, ' name ' VARCHAR (+ ) not null, ' sex ' BOOL not NU LL DEFAULT ' 1 ', ' birthyear ' INT not NULL)
You want to read all data from the people data table after the date of birth in the specified year. The PHP code is very simple:
1. Connect to a database
2. Run the SQL query, which has a block of data based on the Post/get value in JSON format.
For example, this feature is available in the getallpeoplebornafter.php file:
[Java]View PlainCopy
- '. $_request[' year']. "'"; while ($e =mysql_fetch_assoc ($q)) $output []= $e;p rint (Json_encode ($output)); Mysql_close ();? >
The Android section is a bit more complicated:
1. Use httppost to get data, send year value
2. The response information is converted into characters
3. Parse the JSON data and read the data you want.
[Java]View PlainCopy
- String result ="";The year data to sendarraylist namevaluepairs = newarraylist (); Namevaluepairs.add (New basicnamevaluepair ("Year", "1980"));//http posttry{ httpclient Httpclient = new defaulthttpclient (); httppost httppost = newhttppost ("http ://example.com/getallpeoplebornafter.php "); httppost.setentity (New urlencodedformentity ( Namevaluepairs)); httpresponse response = httpclient.execute (httppost); HttpEntity entity = response.getentity (); inputstream is = entity.getcontent ();} catch (exception e) { log.e ("Log_tag", "error in http connection " +e.toString ());} convert response to stringtry{ bufferedreader reader = new BufferedReader (New inputstreamreader (IS, "iso-8859-1"), 8); stringbuilder sb = new stringbuilder (); string line = null; while ((Line = reader.readline ()) != null) { sb.append (line + "\ n"); } is.close (); result=sb.tostring ();} catch (exception e) { log.e ("Log_tag", "error converting result " +e.toString ());} Parse json datatry{ jsonarray jarray = new jsonarray (result); for ( int i=0;i
Of course, you can also use HTTPS, send passwords, Access data , or do more complex data processing on each side, and write more code.
-
Top
-
0
-
Step
How Android connects to MySQL database