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 -->
分享到:
相关推荐
There's also robust coverage of connecting to MySQL NDB Cluster from Java, SQL, memcached, and even from C++. From any of these languages, you'll be able to connect and store and retrieve data as ...
kettle连接Oracle报错kettle连接Oracle报错报错信息 kettle连接Oracle报错 ...Error connecting to database: (using class oracle.jdbc.driver.OracleDriver) Listener refused the connection with th
2 How It Fits Together: Connecting to MySQL 59 3 Creating Your Own Data: Create and Populate a Database 103 4 Your Application on the Web: Realistic and Practical Applications 159 5 When a Database ...
Expert PHP and MySQL takes you beyond learning syntax to showing you how to apply proven software development methods to building commerce-grade PHP and MySQL projects that will stand the test of time...
Use MySQL Shell, the first modern and advanced client for connecting to and interacting with MySQL. It supports SQL, Python, and JavaScript. That’s right! You can write Python scripts and execute ...
* PHP Bridges for connecting to MySQL, PostgreSQL, and SQL Server databases remotely via PHP enabled web servers * An ASP bridge for connecting to MS SQL Server databases remotely via ASP enabled web ...
TransactionRetry.apply_activerecord_patch # after connecting to the database 连接到数据库后。 重试的数据库死锁和序列化错误 MySQL 尝试获取锁时发现死锁 超过锁定等待超时 PostgreSQL 检测到死锁
labview_连接各类数据库工具包,MySQL serverSQL Access(Connecting various database Toolkits)
Table of Contents Preface, Notes, Licenses . . . . . . . . ....1. Licenses for Third-Party Components ....1.1. FindGTest.cmake License ....1.2. LPeg Library License ....1.3. LuaFileSystem Library License ....
PHP's database access functions are not ... We have had successful reports of connecting to Progress, SQLite and DB2 via ODBC. We hope more people will contribute drivers to support other databases. ...
[2018-05-28 17:37:01] INFO Connecting to mysql... [2018-05-28 17:37:01] INFO Querying forts... [2018-05-28 17:37:01] INFO Migrating forts... [2018-05-28 17:37:49] 8292/8292 [=================
sql MySQL pipe What does it do? sql allows you to pipe STDIN (hopefully containing SQL) to one or more pre-configured ...sql can either run mysql/psql locally, run mysql/psql locally but connecting to
conn.isClosed()) { System.out.println("Succeeded connecting to the Database!"); } else { System.out.println("Falled connecting to the Database!"); } }catch(Exception ex){ ex.printStackTrace(); } ...
Installing inquirer, running npm i through ypur terminal, and connecting a mysql database 用法 使用index.js在命令行中运行,并按照说明和提示进行操作 执照 该项目已获得MIT许可。 贡献 允许用户删除员工...
Identify the Steps for Connecting to the Database 256 Write the Code to Create a Table in the Database 259 Write the Code to Insert the Registration Details into the Table Created 260 Execute the ...
#Sublime 文字引述有了这个应用程序,你基本上可以阅读一些不错的励志名言,我用一个名为Simple HTML DOM Parser的库做了一个... We had some issues connecting to the database: ".mysql_error());($db) ? "" : die
connecting to the following SQL servers using 32-bit native application programming interfaces (API): Centura SQLBase Server 6(+), IBM DB2 Universal Database with CAE v5.2, Informix Server 7.2(+), ...
集合Java源码MySQL连接源代码 小型示例控制台源代码如何连接到MySQL,如何更新行以及如何读取表。 在Windows下运行 将此存储库克隆到您的计算机 安装MySQL (作为Docker容器) 准备用户,数据库中的表和行 构建并...
12.2 CONNECTING TO A DATABASE 261 12.3 CREATING A MYSQL DATABASE 262 12.3.1 Creating Tables 263 12.3.2 Loading a Table 264 12.4 PLANNING AHEAD 266 12.4.1 PythonU: Sample Database 266 12.5 SELECT: ...
关于 Este proyecto美国PHP,AJAX,BOOTSTRAP 3,MySql和Alertify。 安装 ...$dbconfig = mysqli_connect($host,$username,$password,$database) or die("An Error occured while connecting to th