`

Connecting to MySQL database【转】

阅读更多
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 -->
分享到:
评论

相关推荐

    VC-connecting-to-MYSQL.zip_mysql vc_visual c

    在"VC connecting to MYSQL.doc"文档中,可能包含了更多关于如何在VC++中配置MySQL Connector/C++,如何处理连接错误,以及如何使用C API进行更复杂数据库操作的详细步骤和示例代码。确保仔细阅读并理解这些内容,...

    how to create the database in linux sever

    System.err.println("Error connecting to the database: " + e.getMessage()); } } } ``` 确保在项目中添加了对应的数据库驱动库,例如,对于MySQL,需要添加MySQL Connector/J的JAR文件到类路径中。 最后,...

    mysql8.0jdbc驱动.zip

    System.err.println("Error connecting to the database: " + e.getMessage()); } } } ``` 这里,`url`是数据库服务器的地址,包括端口号(默认3306)和要连接的数据库名。`username`和`password`是你的MySQL...

    Unity连Mysql的MySql.Data.dll,支持Unity2021,Mysql8.0 、Mysql5.5的外网增删改查

    Debug.LogError("Error connecting to MySQL: " + ex.Message); } } ``` **步骤四:执行SQL命令** 现在你可以使用这个连接执行SQL查询、插入、更新和删除操作。例如,执行一个简单的SELECT查询: ```csharp ...

    java连接mysql示例

    System.err.println("Error connecting to database: " + e.getMessage()); } } } ``` 这段代码首先加载了MySQL JDBC驱动,然后使用`DriverManager.getConnection()`方法建立到数据库的连接。注意,URL中包含...

    unity3d连接mysql数据库

    Debug.LogError("Error connecting to MySQL: " + ex.Message); } finally { if (conn != null && conn.State == ConnectionState.Open) { conn.Close(); } } } ``` 在这个例子中,`connStr`是包含数据库连接...

    mysql-connector-java-8.0.23.rar

    System.err.println("Error connecting to the database: " + e.getMessage()); } } } ``` 在这个例子中,`DriverManager.getConnection()`方法用于建立与MySQL服务器的连接。URL指定数据库的位置,包括主机名、...

    ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/tmp/mysql.sock'

    在MySQL服务器的运行过程中,可能会遇到“ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/tmp/mysql.sock'”这样的错误。这个错误提示表明,客户端试图通过Unix域套接字(socket文件)...

    mysql-connector-java-8.0.22

    System.err.println("Error connecting to the database: " + e.getMessage()); } } } ``` 在这个例子中,我们首先导入了必要的`java.sql`包,然后通过`DriverManager.getConnection()`方法建立到数据库的连接。...

    mysql-connector-java-5.1.47-bin.jar .zip

    System.out.println("Error connecting to the database."); e.printStackTrace(); } } } ``` 在这个例子中,`Class.forName("com.mysql.jdbc.Driver")`是用来加载MySQL的JDBC驱动,`DriverManager.get...

    QT 5.15.2 安装MySQL驱动

    qDebug() &lt;&lt; "Error connecting to database:" ().text(); } ``` 6. **编译并运行**: - 编译并运行你的应用程序,如果一切配置正确,你应该能够成功连接到MySQL服务器并执行查询。 以上就是QT 5.15.2中安装和...

    kettle连接Oracle报错

    kettle连接Oracle报错kettle连接Oracle报错报错信息 kettle连接Oracle报错 ...Error connecting to database: (using class oracle.jdbc.driver.OracleDriver) Listener refused the connection with th

    jdbc-mysql-connection

    System.out.println("Error connecting to the database."); e.printStackTrace(); } } } ``` 在上述代码中,我们首先通过`Class.forName()`加载MySQL的JDBC驱动,然后使用`DriverManager.getConnection()`方法...

    mysql-connector-java-8.0.23.jar

    System.err.println("Error connecting to the database: " + e.getMessage()); } } } ``` 总的来说,mysql-connector-java-8.0.23.jar是Java开发者不可或缺的工具,它为与MySQL数据库的交互提供了便利和强大的...

    mysql-connector-java-5.1.35 MySQL的jdbc驱动jar

    System.out.println("Error connecting to the database."); e.printStackTrace(); } } } ``` 在上述代码中,`Class.forName()`方法用于加载驱动,`DriverManager.getConnection()`方法用于建立与数据库的连接...

    mysql连接数据库需要的jar包

    System.err.println("Error connecting to the database: " + e.getMessage()); } } } ``` 在这个例子中,我们使用`DriverManager.getConnection()`方法来建立到MySQL服务器的连接。`url`参数应包含数据库的地址...

    mysql驱动连接5.1.47

    System.err.println("Error connecting to the database: " + e.getMessage()); } } } ``` 在上述代码中,`DriverManager.getConnection()`方法用于建立连接,参数分别是数据库URL、用户名和密码。 5. **处理...

    mysql-connector-java-8.0.9

    System.err.println("Error connecting to the database: " + e.getMessage()); } } } ``` 在上述代码中,`DriverManager.getConnection()`方法用于建立连接,URL指定数据库的地址(包括主机名、端口和数据库名)...

Global site tag (gtag.js) - Google Analytics