我有以下代码用于将带有数据的文本文件加载到mysql表:
private final String filepath = "/mnt/sdcard/acc.txt";
private String acc;
public void insert()
{
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair(filepath,acc));
try
{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://testandroid.net/insert.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
Log.e("pass 1", "connection success ");
}
catch(Exception e)
{
Log.e("Fail 1", e.toString());
Toast.makeText(getApplicationContext(), "Invalid IP Address",
Toast.LENGTH_LONG).show();
}
try
{
BufferedReader reader = new BufferedReader
(new InputStreamReader(is,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
is.close();
result = sb.toString();
Log.e("pass 2", "connection success ");
}
catch(Exception e)
{
Log.e("Fail 2", e.toString());
}
try
{
JSONObject json_data = new JSONObject(result);
code=(json_data.getInt("code"));
if(code==1)
{
Toast.makeText(getBaseContext(), "Inserted Successfully",
Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(getBaseContext(), "Sorry, Try Again",
Toast.LENGTH_LONG).show();
}
}
catch(Exception e)
{
Log.e("Fail 3", e.toString());
}
}
这是我在服务器上的phpfile
<?php
$host='xxx';
$uname='yyy';
$pwd='cfd';
$db="dxw";
$con = mysql_connect($host,$uname,$pwd) or die("connection failed");
mysql_select_db($db,$con) or die("db selection failed");
$id=$_REQUEST['id'];
$name=$_REQUEST['name'];
$flag['code']=0;
if($r=mysql_query("LOAD DATA INFILE '$filepath' INTO TABLE xfr) ",$con))
{
$flag['code']=1;
echo"hi";
}
print(json_encode($flag));
mysql_close($con);
?>
我一直收到无效的IP地址错误。我不知道自己做错了什么。请帮忙。我想在mysql服务器
中加载文本文件答案 0 :(得分:0)
如果它在此行生成异常:
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
这是因为名值对中的空内容或默认编码问题。您可以通过添加utf-8编码将其更改为以下行
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "utf-8"));
答案 1 :(得分:0)
这是一个大错误,或者我是如此虚伪......
您将文件名作为BasicNamevaluePair(http param)的键传递 并且值为空字符串...
private String acc;
public void insert()
{
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair(filepath,acc));
你必须阅读文件内容并传递它们
nameValuePairs.add(new BasicNameValuePair("data",getFileContent(filepath));
在php页面 你读了2个没有从移动应用程序发送的参数
$id=$_REQUEST['id'];
$name=$_REQUEST['name'];
在php页面上,读取参数“data”,将其保存到文件 at server 并将其加载到db
$data=$_REQUEST['data'];
saveFile("myfile.txt", $data);
mysql_query("LOAD DATA INFILE myfile.txt INTO TABLE xfr") ",$con);