Connecting to MySQL database【转】

Android连接MySQL数据库
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. mysql logo

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:

 

  1. CREATE TABLE `people` (
  2. `id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
  3. `name` VARCHAR ( 100 ) NOT NULL ,
  4. `sex` BOOL NOT NULL DEFAULT '1',
  5. `birthyear` INT NOT NULL
  6. )

 

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:

 

  1. <?php
  2. mysql_connect ( "host", "username", "password" ) ;
  3. mysql_select_db ( "PeopleData" ) ;
  4.  
  5. $q =mysql_query ( "SELECT * FROM people WHERE birthyear>'".$_REQUEST [ 'year' ]. "'" ) ;
  6. while ($e =mysql_fetch_assoc ($q ) )
  7.         $output [ ] =$e ;
  8.  
  9. print (json_encode ($output ) ) ;
  10.  
  11. mysql_close ( ) ;
  12. ?>

 

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

 

  1. String result = "" ;
  2. //the year data to send
  3. ArrayList <NameValuePair > nameValuePairs = new ArrayList <NameValuePair > ( ) ;
  4. nameValuePairs. add ( new BasicNameValuePair ( "year", "1980" ) ) ;
  5.  
  6. //http post
  7. try {
  8.         HttpClient httpclient = new DefaultHttpClient ( ) ;
  9.         HttpPost httppost = new HttpPost ( "http://example.com/getAllPeopleBornAfter.php" ) ;
  10.         httppost. setEntity ( new UrlEncodedFormEntity (nameValuePairs ) ) ;
  11.         HttpResponse response = httpclient. execute (httppost ) ;
  12.         HttpEntity entity = response. getEntity ( ) ;
  13.         InputStream is = entity. getContent ( ) ;
  14. } catch ( Exception e ) {
  15.         Log. e ( "log_tag", "Error in http connection " +e. toString ( ) ) ;
  16. }
  17. //convert response to string
  18. try {
  19.         BufferedReader reader = new BufferedReader ( new InputStreamReader (is, "iso-8859-1" ),8 ) ;
  20.         StringBuilder sb = new StringBuilder ( ) ;
  21.         String line = null ;
  22.         while ( (line = reader. readLine ( ) ) != null ) {
  23.                 sb. append (line + "\n" ) ;
  24.         }
  25.         is. close ( ) ;
  26.  
  27.         result =sb. toString ( ) ;
  28. } catch ( Exception e ) {
  29.         Log. e ( "log_tag", "Error converting result " +e. toString ( ) ) ;
  30. }
  31.  
  32. //parse json data
  33. try {
  34.         JSONArray jArray = new JSONArray (result ) ;
  35.         for ( int i = 0 ;i <jArray. length ( ) ;i ++ ) {
  36.                 JSONObject json_data = jArray. getJSONObject (i ) ;
  37.                 Log. i ( "log_tag", "id: " +json_data. getInt ( "id" ) +
  38.                         ", name: " +json_data. getString ( "name" ) +
  39.                         ", sex: " +json_data. getInt ( "sex" ) +
  40.                         ", birthyear: " +json_data. getInt ( "birthyear" )
  41.                 ) ;
  42.         }
  43. }
  44. } catch (JSONException e ) {
  45.         Log. e ( "log_tag", "Error parsing data " +e. toString ( ) ) ;
  46. }

 

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 -->
### 解决 MySQL 连接错误 2003 和 WinError 10061 的方法 当遇到 `django.db.utils.operationalerror:<2003, "can’t connect to mysql server on ‘127.0.0.1’(winerror 10061) No connection could be made because the target machine actively refused it"` 错误时,这通常意味着客户端尝试连接到服务器但被拒绝。以下是可能的原因和解决方案: #### 检查 MySQL 服务状态 确保 MySQL 服务正在运行。可以通过命令提示符或 PowerShell 使用以下命令来启动 MySQL 服务: ```powershell net start MySQL80 ``` 如果服务未启动,则上述命令会启动该服务。 #### 验证端口配置 默认情况下,MySQL 使用 3306 端口进行通信。确认防火墙设置允许通过此端口的流量,并验证 MySQL 是否监听正确的 IP 地址和端口号。可以编辑 my.ini 或 my.cnf 文件中的 `[mysqld]` 部分下的 bind-address 参数[^1]。 #### 修改主机名解析 有时本地环回地址(即 127.0.0.1)可能会引起问题;试着将数据库 URL 中的 host 设置更改为 'localhost' 并重启应用试试看是否有改善效果。 #### 排除其他应用程序占用端口冲突情况 检查是否有其他程序占用了 MySQL 默认使用的 3306 端口。如果有,请停止这些进程或将 MySQL 改为使用另一个可用端口。 #### 测试网络连通性和权限 即使是在同一台机器上操作也应测试能否 ping 到目标地址以及 telnet 至指定端口以排除基本网络层面上的问题。另外需要注意的是,某些时候尽管能够建立 TCP/IP 层面的成功握手但仍无法完成身份认证过程——此时应该参照关于访问控制方面的文档进一步排查原因[^2][^3]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值