如何连接mysql数据库并使用android代码插入数据

时间:2022-09-25 19:19:27

I have mysql database on my hosting server

我的主机服务器上有mysql数据库

On simple android application I have feedback form and on submit I want to insert data into mysql database which is on server .

在简单的android应用程序中,我有反馈表单,提交时,我想将数据插入服务器上的mysql数据库。

I tried google and found this following solution for local machine

我尝试了谷歌,发现了以下本地机器的解决方案

how do I connect to my hosting server and mysql database without any php code?

如何在没有任何php代码的情况下连接到主机服务器和mysql数据库?

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());
    }
    }

2 个解决方案

#1


4  

Here

在这里

HttpPost httppost = new HttpPost("http://10.0.2.2/insert.php");

insert.php is mentioned means you have to put this file on server

插入。提到php意味着您必须将这个文件放在服务器上

just change the http://10.0.2.2/insert.php to the path of your server file path where the file is stored

只是改变了http://10.0.2.2/insert。php到存储文件的服务器文件路径的路径。

Code for 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);
    ?>

as mentioned in your code , this will get the value from server whether the data is stored or not by code=1 for stored and code = 0 for not stored

如您的代码中所提到的,它将从服务器获取数据的值,无论数据是由代码=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();
            }

#2


-2  

package fluent.techno.shreedurgajyotish;

import java.util.ArrayList;

import org.apache.http.NameValuePair;

import org.apache.http.message.BasicNameValuePair;

import org.json.JSONArray;

import org.json.JSONException;

import org.json.JSONObject;

import fluentindia.database.mysql.JsonHelper;

import fluentindia.tech.MenuAdapter.ProductAdapter;

import fluentindia.tech.MenuModel.ProductModel;

import android.app.ProgressDialog;

import android.content.Intent;

import android.net.Uri;

import android.os.AsyncTask;

import android.os.Bundle;

import android.support.v4.app.Fragment;

import android.util.Log;

import android.view.LayoutInflater;

import android.view.View;

import android.view.ViewGroup;

import android.view.View.OnClickListener;

import android.widget.AdapterView;

import android.widget.Button;

import android.widget.EditText;

import android.widget.Spinner;

import android.widget.TextView;

import android.widget.Toast;

import android.widget.AdapterView.OnItemSelectedListener;

public class Feedback extends Fragment
{
    Button close,home,btnback,btnsend;

EditText edname,edcompany,edemail,edcontact,edwebsite,edaddress,edcomment;

String  na,con,email,comm,advname,advem,advcontact,nacompany,web,add;

Spinner product;

JsonHelper Jobj;

String WebUrl, UrlImg;

JSONObject obj = null;

String Id,name,em,contact,AdvocateId,city;

ProductAdapter madappppppppppp;

ArrayList<ProductModel> llistttt;

int proid=0;

TextView textViewt2,t1;

public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
}
public View onCreateView(LayoutInflater inflater,ViewGroup container,Bundle savedInstanceState)
{
    View v =inflater.inflate(R.layout.feedback, null);  
    edname = (EditText)v.findViewById(R.id.editname);
    edemail = (EditText)v.findViewById(R.id.editemail);
    edcontact = (EditText)v.findViewById(R.id.editcontact);
    edcomment = (EditText)v.findViewById(R.id.editcomment);
    btnsend = (Button)v.findViewById(R.id.btnsend);
    product = (Spinner)v.findViewById(R.id.editproduct);
    textViewt2 = (TextView)v.findViewById(R.id.textViewt2);
    t1 = (TextView)v.findViewById(R.id.textView1);
    Bundle bung = this.getArguments();
    if(bung!=null)
    {
        proid = bung.getInt("proid");
    }
    if(proid == 0)
    {
    Processtaluka pro = new Processtaluka();
    pro.executeOnExecutor(pro.THREAD_POOL_EXECUTOR, new String[]{"selectdistict.php"});
    }
    else
    {
        Processtaluka pro = new Processtaluka();
        pro.executeOnExecutor(pro.THREAD_POOL_EXECUTOR, new String[]{"selectsingledistict.php?proid="+proid});
    }
    t1.setOnClickListener(new OnClickListener() 
    {
        @Override
        public void onClick(View v) {
             Intent callweb = new Intent(Intent.ACTION_VIEW);
             callweb.setData(Uri.parse("http://pulleycoupling.com/"));
             startActivity(callweb);
        }
    });
    textViewt2.setOnClickListener(new OnClickListener() 
    {
        @Override
        public void onClick(View v) {
             Intent callIntent = new Intent(Intent.ACTION_CALL);
             callIntent.setData(Uri.parse("tel:9824155380"));
             startActivity(callIntent);
        }
    });
    btnsend.setOnClickListener(new OnClickListener()
    {
        @Override
        public void onClick(View v)
        {
            na=edname.getText().toString();
            con=edcontact.getText().toString();
            email=edemail.getText().toString();
            comm = edcomment.getText().toString();
            if(na==null||na==""||na.length()<2)
            {
                edname.setError("Please Enter  Name");
            }
            else if(con == null || con == "" || con.length()<10)
            {
                edcontact.setError("Please Enter Contact");
            }
            else if(email == null || email == "" || email.length()<4)
            {
                edemail.setError("Please Enter Email");
            }
            else if(comm == null || comm== "" || comm.length()<2)
            {
                edcomment.setError("Please Enter Comment");
            }
            else 
            {
                    ProcessInquiry pro = new ProcessInquiry();
                    pro.execute(new String[]{"insertfeedback.php"});
            }
        }
    });
    return v;
}
private class ProcessInquiry extends AsyncTask<String, Void, Boolean>
{
    ProgressDialog dialog = new ProgressDialog(getActivity());
    @Override
    protected void onPreExecute()
    {
        dialog.setMessage("Please Wait Feedback send..");
        dialog.show();
    }
    @Override
    protected Boolean doInBackground(String... Url) 
    {
        for(String Url1 : Url)
        {
            try
            {
                Jobj = new JsonHelper();
                ArrayList<NameValuePair> pair = new ArrayList<NameValuePair>();
                pair.add(new BasicNameValuePair("name", na));
                pair.add(new BasicNameValuePair("contact", con));
                pair.add(new BasicNameValuePair("email", email));
                pair.add(new BasicNameValuePair("comment", comm));
                pair.add(new BasicNameValuePair("product", city));
                Jobj.MakeJsonCall(Url1, 2, pair);
                Log.e("Url", Url1);
                return true;
            }
            catch (Exception e)
            {
                return false;
            }
        }
        return true;
    }
    @Override
    protected void onPostExecute(Boolean result)
    {
        if(result==true)
        {
            Toast.makeText(getActivity(), "Feedback Send Sucessfully", 1000).show();

                Intent i=new Intent(getActivity(),FragmentMaster.class);
                i.putExtra("frgNo", "0");
                startActivity(i);

            edname.setText("");
            edcomment.setText("");
            edcontact.setText("");
            edemail.setText("");
        }
        dialog.dismiss();
    }
}
private class Processtaluka extends AsyncTask<String, Void, Boolean>
{
    @Override
    protected void onPreExecute()
    {
    }
    @Override
    protected Boolean doInBackground(String... Url) 
    {
        for(String Url1 : Url)
        {
                Jobj = new JsonHelper();
                obj = Jobj.MakeJsonCall(Url1, 2);
                try 
                {
                    llistttt = new ArrayList<ProductModel>();
                    JSONArray JArr = obj.getJSONArray("record");
                    if(proid == 0)
                    {
                    }
                    else
                    {
                    }
                    for(int i=0;i<JArr.length();i++)
                    {
                        JSONObject dObj = JArr.getJSONObject(i);
                        llistttt.add(new ProductModel( dObj.getString("sub_id"), dObj.getString("sub_name")));
                    }
                } 
                catch (JSONException e) 
                {
                    e.printStackTrace();
                }
                return true;
            }
        return true;
    }
    @Override
    protected void onPostExecute(Boolean result)
    {
        madappppppppppp = new ProductAdapter(getActivity(),llistttt);
        product.setAdapter(madappppppppppp);
        product.setPrompt("Select The Service You Want");
        product.setOnItemSelectedListener(new OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> arg0, View arg1,
                    int arg2, long arg3) {

                 city= llistttt.get(arg2).getSubname();
            }
            @Override
            public void onNothingSelected(AdapterView<?> arg0) {
            }
        });
    }
  }
}

#1


4  

Here

在这里

HttpPost httppost = new HttpPost("http://10.0.2.2/insert.php");

insert.php is mentioned means you have to put this file on server

插入。提到php意味着您必须将这个文件放在服务器上

just change the http://10.0.2.2/insert.php to the path of your server file path where the file is stored

只是改变了http://10.0.2.2/insert。php到存储文件的服务器文件路径的路径。

Code for 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);
    ?>

as mentioned in your code , this will get the value from server whether the data is stored or not by code=1 for stored and code = 0 for not stored

如您的代码中所提到的,它将从服务器获取数据的值,无论数据是由代码=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();
            }

#2


-2  

package fluent.techno.shreedurgajyotish;

import java.util.ArrayList;

import org.apache.http.NameValuePair;

import org.apache.http.message.BasicNameValuePair;

import org.json.JSONArray;

import org.json.JSONException;

import org.json.JSONObject;

import fluentindia.database.mysql.JsonHelper;

import fluentindia.tech.MenuAdapter.ProductAdapter;

import fluentindia.tech.MenuModel.ProductModel;

import android.app.ProgressDialog;

import android.content.Intent;

import android.net.Uri;

import android.os.AsyncTask;

import android.os.Bundle;

import android.support.v4.app.Fragment;

import android.util.Log;

import android.view.LayoutInflater;

import android.view.View;

import android.view.ViewGroup;

import android.view.View.OnClickListener;

import android.widget.AdapterView;

import android.widget.Button;

import android.widget.EditText;

import android.widget.Spinner;

import android.widget.TextView;

import android.widget.Toast;

import android.widget.AdapterView.OnItemSelectedListener;

public class Feedback extends Fragment
{
    Button close,home,btnback,btnsend;

EditText edname,edcompany,edemail,edcontact,edwebsite,edaddress,edcomment;

String  na,con,email,comm,advname,advem,advcontact,nacompany,web,add;

Spinner product;

JsonHelper Jobj;

String WebUrl, UrlImg;

JSONObject obj = null;

String Id,name,em,contact,AdvocateId,city;

ProductAdapter madappppppppppp;

ArrayList<ProductModel> llistttt;

int proid=0;

TextView textViewt2,t1;

public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
}
public View onCreateView(LayoutInflater inflater,ViewGroup container,Bundle savedInstanceState)
{
    View v =inflater.inflate(R.layout.feedback, null);  
    edname = (EditText)v.findViewById(R.id.editname);
    edemail = (EditText)v.findViewById(R.id.editemail);
    edcontact = (EditText)v.findViewById(R.id.editcontact);
    edcomment = (EditText)v.findViewById(R.id.editcomment);
    btnsend = (Button)v.findViewById(R.id.btnsend);
    product = (Spinner)v.findViewById(R.id.editproduct);
    textViewt2 = (TextView)v.findViewById(R.id.textViewt2);
    t1 = (TextView)v.findViewById(R.id.textView1);
    Bundle bung = this.getArguments();
    if(bung!=null)
    {
        proid = bung.getInt("proid");
    }
    if(proid == 0)
    {
    Processtaluka pro = new Processtaluka();
    pro.executeOnExecutor(pro.THREAD_POOL_EXECUTOR, new String[]{"selectdistict.php"});
    }
    else
    {
        Processtaluka pro = new Processtaluka();
        pro.executeOnExecutor(pro.THREAD_POOL_EXECUTOR, new String[]{"selectsingledistict.php?proid="+proid});
    }
    t1.setOnClickListener(new OnClickListener() 
    {
        @Override
        public void onClick(View v) {
             Intent callweb = new Intent(Intent.ACTION_VIEW);
             callweb.setData(Uri.parse("http://pulleycoupling.com/"));
             startActivity(callweb);
        }
    });
    textViewt2.setOnClickListener(new OnClickListener() 
    {
        @Override
        public void onClick(View v) {
             Intent callIntent = new Intent(Intent.ACTION_CALL);
             callIntent.setData(Uri.parse("tel:9824155380"));
             startActivity(callIntent);
        }
    });
    btnsend.setOnClickListener(new OnClickListener()
    {
        @Override
        public void onClick(View v)
        {
            na=edname.getText().toString();
            con=edcontact.getText().toString();
            email=edemail.getText().toString();
            comm = edcomment.getText().toString();
            if(na==null||na==""||na.length()<2)
            {
                edname.setError("Please Enter  Name");
            }
            else if(con == null || con == "" || con.length()<10)
            {
                edcontact.setError("Please Enter Contact");
            }
            else if(email == null || email == "" || email.length()<4)
            {
                edemail.setError("Please Enter Email");
            }
            else if(comm == null || comm== "" || comm.length()<2)
            {
                edcomment.setError("Please Enter Comment");
            }
            else 
            {
                    ProcessInquiry pro = new ProcessInquiry();
                    pro.execute(new String[]{"insertfeedback.php"});
            }
        }
    });
    return v;
}
private class ProcessInquiry extends AsyncTask<String, Void, Boolean>
{
    ProgressDialog dialog = new ProgressDialog(getActivity());
    @Override
    protected void onPreExecute()
    {
        dialog.setMessage("Please Wait Feedback send..");
        dialog.show();
    }
    @Override
    protected Boolean doInBackground(String... Url) 
    {
        for(String Url1 : Url)
        {
            try
            {
                Jobj = new JsonHelper();
                ArrayList<NameValuePair> pair = new ArrayList<NameValuePair>();
                pair.add(new BasicNameValuePair("name", na));
                pair.add(new BasicNameValuePair("contact", con));
                pair.add(new BasicNameValuePair("email", email));
                pair.add(new BasicNameValuePair("comment", comm));
                pair.add(new BasicNameValuePair("product", city));
                Jobj.MakeJsonCall(Url1, 2, pair);
                Log.e("Url", Url1);
                return true;
            }
            catch (Exception e)
            {
                return false;
            }
        }
        return true;
    }
    @Override
    protected void onPostExecute(Boolean result)
    {
        if(result==true)
        {
            Toast.makeText(getActivity(), "Feedback Send Sucessfully", 1000).show();

                Intent i=new Intent(getActivity(),FragmentMaster.class);
                i.putExtra("frgNo", "0");
                startActivity(i);

            edname.setText("");
            edcomment.setText("");
            edcontact.setText("");
            edemail.setText("");
        }
        dialog.dismiss();
    }
}
private class Processtaluka extends AsyncTask<String, Void, Boolean>
{
    @Override
    protected void onPreExecute()
    {
    }
    @Override
    protected Boolean doInBackground(String... Url) 
    {
        for(String Url1 : Url)
        {
                Jobj = new JsonHelper();
                obj = Jobj.MakeJsonCall(Url1, 2);
                try 
                {
                    llistttt = new ArrayList<ProductModel>();
                    JSONArray JArr = obj.getJSONArray("record");
                    if(proid == 0)
                    {
                    }
                    else
                    {
                    }
                    for(int i=0;i<JArr.length();i++)
                    {
                        JSONObject dObj = JArr.getJSONObject(i);
                        llistttt.add(new ProductModel( dObj.getString("sub_id"), dObj.getString("sub_name")));
                    }
                } 
                catch (JSONException e) 
                {
                    e.printStackTrace();
                }
                return true;
            }
        return true;
    }
    @Override
    protected void onPostExecute(Boolean result)
    {
        madappppppppppp = new ProductAdapter(getActivity(),llistttt);
        product.setAdapter(madappppppppppp);
        product.setPrompt("Select The Service You Want");
        product.setOnItemSelectedListener(new OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> arg0, View arg1,
                    int arg2, long arg3) {

                 city= llistttt.get(arg2).getSubname();
            }
            @Override
            public void onNothingSelected(AdapterView<?> arg0) {
            }
        });
    }
  }
}