这是我第一次尝试让 Android 应用程序与存储在远程服务器上的 MySQL 数据库进行交互。此时我想做的就是将一条记录插入到一个空的远程表中。基本上,我只是尝试建立连接并写入非常简单的数据。
我没有收到任何错误,但运行后我的表仍然是空的。我做错了什么???
/my_db/test.php
include('connection.php');
$name='dummy';
$sql = "INSERT INTO test (name) VALUES ('$name')";
$result = mysql_query($sql);
if(!$result) {return -1;}
return 1;
?>
这是在我的 Activity 的 onCreate 函数中:
btnRegister.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
//Avoiding threading issues for the moment
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
DefaultHttpClient httpclient = new DefaultHttpClient();
String testURL = context.getResources().getString(R.string.dbURL) + "my_db/test.php";
System.err.println(testURL); //output looks good 'http://XXX.XXX.XXX.XXX/my_db/test.php'
HttpPost httppost = new HttpPost(testURL);
try
{
//not actually using the passed parameter for now
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("name", inputFullName.getText().toString()));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
System.err.println("done");
}
catch(Exception e)
{
System.err.println("error");
e.printStackTrace();
}
}
});
最佳答案
您可能会检查服务器响应或http响应,因为看起来代码实际上连接到服务器端,但服务器端无法执行查询,您可以先尝试在Web浏览器中尝试服务器端.
关于php - Android 与 MySQL 数据库的基本交互,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18044840/