我的托管服务器上有mysql数据库
在简单的Android应用程序上我有反馈表单,在提交时我想将数据插入到服务器上的MysqL数据库中.
我试过谷歌,发现以下本地机器的解决方案
how do I connect to my hosting server and MysqL database without any PHP code?
public voID insert() { ArrayList<nameValuePair> nameValuePairs = new ArrayList<nameValuePair>(); nameValuePairs.add(new BasicnameValuePair("ID",ID)); nameValuePairs.add(new BasicnameValuePair("name",name)); try { httpClIEnt httpclIEnt = new DefaulthttpClIEnt(); httpPost httppost = new httpPost("http://10.0.2.2/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()); } }
解决方法:
这里
httpPost httppost = new httpPost("http://10.0.2.2/insert.PHP");
提到insert.PHP意味着你必须把这个文件放在服务器上
只需将http://10.0.2.2/insert.PHP更改为存储文件的服务器文件路径
insert.PHP的代码
// this variables is used for connecting to database and server $host="yourhost"; $uname="username"; $pwd='pass'; $db="dbname"; // this is for connecting $con = MysqL_connect($host,$uname,$pwd) or dIE("connection Failed"); MysqL_select_db($db,$con) or dIE("db selection Failed"); // getting ID and name from the clIEnt if(isset($_REQUEST)){ $ID=$_REQUEST['ID']; $name=$_REQUEST['name'];} // variable used to tell the clIEnt whether data is stored in database or not $flag['code']=0; // for insertion if($r=MysqL_query("insert into emp_info values('$name','$ID') ",$con)) { //if insertion succeed set code to 1 $flag['code']=1; echo"hi"; } // send result to clIEnt that will be 1 or 0 print(Json_encode($flag)); //close MysqL_close($con); ?>
正如您的代码中所提到的,这将从服务器获取数据是否存储数据,代码= 1表示存储,代码= 0表示未存储
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(); }
总结 以上是内存溢出为你收集整理的如何使用android代码连接mysql数据库并将数据插入其中全部内容,希望文章能够帮你解决如何使用android代码连接mysql数据库并将数据插入其中所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)