"Go" Connection MySQL database (android,php,mysql)

Source: Internet
Author: User

The simplest and most convenient way to manage a MySQL database is the php script.
Run the PHP script using the HTTP protocol and the Android system connection.
We encode the data in JSON format because both Android and PHP have ready-made JSON functions.

The following sample code, which reads data from a database according to a given condition, is converted to JSON data.
The HTTP protocol is passed to android,android parsing JSON data.

Definitions in MySQL have the following table, and there are some data

1 CREATE TABLE' People ' (2' ID 'INT  not NULLAuto_incrementPRIMARY KEY ,3' Name 'VARCHAR( -) not NULL ,4' Sex ' BOOL not NULL DEFAULT '1',5' Birthyear 'INT  not NULL6)
View Code

We want to get data about people born in a given year.
The PHP code will be very simple: connect to the database-run an SQL query, get the data based on the set where statement block-the conversion is output in JSON format
For example we will have this feature getallpeoplebornafter.php file:

1<?PHP2 /*connecting to a database*/3 mysql_connect("Host", "username", "password");4 mysql_select_db("Peopledata");5 /*$_request[' year ' gets the annual value that Android sends, stitching up an SQL query statement*/6 $q=mysql_query("SELECT * from people WHERE birthyear> '".$_request[' Year ']. "'"); 7  while($e=Mysql_fetch_assoc($q))8         $output[]=$e;9 /*conversion output in JSON format*/Ten Print(Json_encode ($output)); One  A Mysql_close(); -?>
View Code

The android part is just a little bit more complicated: sending an annual value with HttpPost, getting the data--transforming the response string--parsing the JSON data.
Finally use it.

1String result = "";2 /*set the year value of the Send*/3Arraylist<namevaluepair> Namevaluepairs =NewArraylist<namevaluepair>();4Namevaluepairs.add (NewBasicnamevaluepair ("Year", "1980"));5 6 /*send an annual value with HttpPost*/7 Try{8HttpClient HttpClient =Newdefaulthttpclient ();9HttpPost HttpPost =NewHttpPost ("http://example.com/getAllPeopleBornAfter.php");//The URL above where PHP is locatedTenHttppost.setentity (Newurlencodedformentity (Namevaluepairs)); OneHttpResponse response =Httpclient.execute (httppost); Ahttpentity entity =response.getentity (); -InputStream is =entity.getcontent (); -}Catch(Exception e) { theLOG.E ("Log_tag", "Networking Error" +e.tostring ()); - } - /*Convert response string*/ - Try{ +BufferedReader reader =NewBufferedReader (NewInputStreamReader (IS, "iso-8859-1"), 8);//Note the "iso-8859-1" encoding does not support Chinese.  -         /*If you want to support Chinese, set MySQL to UTF8 format, also set UTF8 read in this*/ +StringBuilder SB =NewStringBuilder (); AString line =NULL; at          while(line = Reader.readline ())! =NULL) { -Sb.append (line + "\ n")); -         } - is.close (); -  -result=sb.tostring (); in}Catch(Exception e) { -LOG.E ("Log_tag", "Conversion response string Error" +e.tostring ()); to } +  - /*parsing JSON data*/ the Try{ *Jsonarray Jarray =NewJsonarray (result); $          for(intI=0;i<jarray.length (); i++){Panax NotoginsengJsonobject Json_data =Jarray.getjsonobject (i); -LOG.I ("Log_tag", "ID:" +json_data.getint ("id") + the", Name:" +json_data.getstring ("name") + +", Sex:" +json_data.getint ("sex") + A", Birthyear:" +json_data.getint ("Birthyear") the                 ); +         } - } $}Catch(jsonexception e) { $LOG.E ("Log_tag", "Parsing JSON data error" +e.tostring ()); -}
View Code

Note: android4.0 above network code can only be placed on child threads

"Go" Connection MySQL database (android,php,mysql)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.