首先在你的mysql数据库查询select * from user
看裏面有没有允许远程用户访问的帐号,如果没有的话就建立一个。
帐号用%如下图截图部分
Android客户端直接连接远程MySQL数据库的方法如下:String result = ""
//首先使用NameValuePair封装将要查询的年数和关键字绑定
ArrayList<NameValuePair>nameValuePairs = new ArrayList<NameValuePair>()
nameValuePairs.add(new BasicNameValuePair("year","1980"))
//使用HttpPost封装整个SQL语句
//使用HttpClient发送HttpPost对象
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()
InputStream is = entity.getContent()
}catch(Exception e){
Log.e("log_tag", "Error in http connection "+e.toString())
}
//将HttpEntity转化为String
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8)
StringBuilder sb = new StringBuilder()
String line = null
while ((line = reader.readLine()) != null) {
sb.append(line + "\n")
}
is.close()
result=sb.toString()
}catch(Exception e){
Log.e("log_tag", "Error converting result "+e.toString())
}
//将String通过JSONArray解析成最终结果
try{
JSONArray jArray = new JSONArray(result)
for(int i=0i<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())
}
虽然Android开发中可以直接连接数据库,但是实际中却不建议这么做,应该使用服务器端中转下完成。
你是web还是软件上?是怕被注入了执行SQL命令,而不安全吗?
这个,可以使用个中间件做中转吗。
比如web的PHP中,是由后端对数据库进行 *** 作,安全些。
如果是桌面软件上可以考虑使用网络通讯做中转,服务器上的通讯服务端连接mysql进行 *** 作,这样就安全。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)