我想在我的 Android 应用程序中使用一些参数执行插入查询。
例如在 php
中,它类似于:-
$query ="insert into inventoryproductrel(id, productid, sequence_no, quantity, listprice) values(?,?,?,?,?)";
$qparams = array($id,$prod['prod'],$counter,$prod['pcs'],$prod['price']);
$productadded=$adb->pquery($query,$qparams);
这里 pquery
是一个函数:-
function pquery($sql, $params){
global $log, $default_charset;
$log->debug('Prepared sql query being executed : '.$sql);
$this->checkConnection();
$this->executeSetNamesUTF8SQL();
$sql_start_time = microtime(true);
$params = $this->flatten_array($params);
if (count($params) > 0) {
$log->debug('Prepared sql query parameters : [' . implode(",", $params) . ']');
}
if($this->avoidPreparedSql || empty($params)) {
$sql = $this->convert2Sql($sql, $params);
$result = &$this->database->Execute($sql);
} else {
$result = &$this->database->Execute($sql, $params);
}
$sql_end_time = microtime(true);
$this->logSqlTiming($sql_start_time, $sql_end_time, $sql, $params);
$this->lastmysqlrow = -1;
return $result;
}
我不知道如何执行此操作,即在 java/android 中使用参数执行查询。
最佳答案
您可以从 Android 应用程序向同一 PHP 脚本发出 POST 请求,并在将值插入数据库之前,设置 POST 参数中的变量值。
使用以下代码发出 POST 请求。确保从 AsyncTask 或单独的线程执行此操作:
public String makePOSTRequestNew(String urlString,
List<NameValuePair> nameValuePairs) {
URL url;
String response = "";
try {
url = new URL(urlString);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(
os, "UTF-8"));
writer.write(getQuery(nameValuePairs));
writer.flush();
writer.close();
os.close();
InputStream responseStream = new BufferedInputStream(
conn.getInputStream());
BufferedReader responseStreamReader = new BufferedReader(
new InputStreamReader(responseStream));
String line = "";
StringBuilder stringBuilder = new StringBuilder();
while ((line = responseStreamReader.readLine()) != null) {
stringBuilder.append(line);
}
responseStreamReader.close();
response = stringBuilder.toString();
conn.connect();
} catch (IOException e) {
e.printStackTrace();
}
return response;
}
getQuery()
方法从 nameValuePairs 创建参数字符串:
private String getQuery(List<NameValuePair> params)
throws UnsupportedEncodingException {
StringBuilder result = new StringBuilder();
boolean first = true;
for (NameValuePair pair : params) {
if (first)
first = false;
else
result.append("&");
result.append(URLEncoder.encode(pair.getName(), "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(pair.getValue(), "UTF-8"));
}
return result.toString();
}
这就是您如何使用要 POST 的参数调用方法:
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("paramName",
paramValue));
String insertResponse = makePOSTRequestNew(insertURL, nameValuePairs);
关于java - 如何发送带参数的查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25196795/