Java 如何在android中通过eclipse连接mysql

Java 如何在android中通过eclipse连接mysql,java,android,mysql,Java,Android,Mysql,我正在尝试连接到android eclipse中的mysql数据库,并且正在使用 mysql-connector-java-3.1.12-bin。 但它向我显示了一条信息:由于底层异常而失败。 它还没有连接,我用同样的东西在netbeans中连接到我的Java程序。 任何帮助都将不胜感激 package com.bookapp import java.sql.SQLException; import android.os.Bundle; import android.v

我正在尝试连接到android eclipse中的mysql数据库,并且正在使用 mysql-connector-java-3.1.12-bin。 但它向我显示了一条信息:由于底层异常而失败。 它还没有连接,我用同样的东西在netbeans中连接到我的Java程序。 任何帮助都将不胜感激

package com.bookapp

    import java.sql.SQLException;

    import android.os.Bundle;
    import android.view.View;
    import android.view.View.OnClickListener;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.Spinner;
    import android.widget.Toast;
    import android.app.Activity;
    import android.content.Intent;

    public class PersonalInfo extends Activity {


        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.personalinfo);



            try
            {
                StudentDA stud= new StudentDA();
                for (String jshdjsd: stud.GetAllUniversities()) {
                    Toast tt=Toast.makeText(PersonalInfo.this, jshdjsd,Toast.LENGTH_LONG);
                    tt.show();
                }
            //for eastud.GetAllUniversities()));
            }
            catch(SQLException ss)
            {
                Toast tt=Toast.makeText(PersonalInfo.this, "You have an Error "+ss.getMessage(),Toast.LENGTH_LONG);
                tt.show();
            }



            //create reference to layout widget/control
            Button btnNext=(Button) findViewById(R.id.btnNext);

            //create reference to textbox
            final   EditText txtStudNo,txtName,txtSurname;  // text box
            final Spinner cmbGender=(Spinner) findViewById(R.id.cmbGender); // combo box

           txtStudNo=(EditText) findViewById(R.id.txtStudentNo);

           txtName=(EditText) findViewById(R.id.txtName);

           txtSurname=(EditText) findViewById(R.id.txtSurname);


           //set the button onclick event listener
           btnNext.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub


                if (txtStudNo.getText().toString().equals(""))
                {
                    Toast tt=Toast.makeText(PersonalInfo.this, "Please Enter Student No", Toast.LENGTH_LONG);
                    tt.show();
                }
                else if (txtName.getText().toString().equals(""))
                {
                    Toast tt=Toast.makeText(PersonalInfo.this, "Please Enter Name", Toast.LENGTH_LONG);
                    tt.show();
                }
                else if (txtSurname.getText().toString().equals(""))
                {
                    Toast tt=Toast.makeText(PersonalInfo.this, "Please Enter Surname", Toast.LENGTH_LONG);
                    tt.show();
                }
                else if (cmbGender.getSelectedItemPosition()==0)
                {
                    Toast tt=Toast.makeText(PersonalInfo.this, "Please Select Gender", Toast.LENGTH_LONG);
                    tt.show();
                }
                else
                {
                    Student.Gender=cmbGender.getSelectedItem().toString();
                    Student.studentNo=txtStudNo.getText().toString();
                    Student.Name=txtName.getText().toString();
                    Student.Surname=txtSurname.getText().toString();

                    // Go to the next form 

                    Intent i = new Intent (PersonalInfo.this,ContactInfo.class);
                    startActivity(i);

                    //////End of me next 


                    //Toast tt=Toast.makeText(PersonalInfo.this, "Thanks "+     Student.Name, Toast.LENGTH_LONG);
                //  tt.show();
                }



            }
        });

        }


    }

您无法将mysql数据库与android连接。您可以使用webservices调用数据库。Web服务的一些示例是SOAP和RESTFUL。您可以使用其中一个调用db

请参阅以下示例以调用webservice:


您可以使用SQLLite在ANDROID中创建迷你数据库。谷歌在SQLLite上获得更多细节

在Eclipse中创建java项目

创建包名
com.example.sql

在项目中包括
mysqlconnector.jar

下面是本地系统的代码

package com.example.employeeinduction;


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.json.JSONException;
import org.json.JSONObject;


import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.nfc.Tag;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity
{
    public EditText uname,pwd;
    Button btnlog1;
    TextView invalid;
    public Button btncancel1;
    public String db_select;
     String mUname;
     String mPwd;
    String temp;
    Intent intObj;
    Intent intent = null;
    SessionManager session;
Boolean isInternetPresent = false;
    ConnectionDetector cd;

    private String SERVICE_URL = "http://10.54.3.208:8080/";
    private final String SERVICE_URL = Urlmanager.Address;
    private final String TAG = "MainActivity";
    public static final String PREFS_NAME = "MyPrefsFile";
    public static final String Is_Login = "Is_Login";
    public static final String MyPREFERENCES = "MyPREFERENCES";
    private static final String IS_USER_LOGIN = "IsUserLoggedIn";
    @Override
    protected void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        MainActivity.this.setContentView(R.layout.activity_main);
        uname=(EditText)findViewById(R.id.editText1);
        pwd=(EditText)findViewById(R.id.editText2);
        invalid=(TextView)findViewById(R.id.textView3);
        btnlog1=(Button)findViewById(R.id.button1);
          session = new SessionManager(getApplicationContext()); 
        btnlog1.setOnClickListener(new View.OnClickListener()
        {           
            @Override
            public void onClick(View v) 
            {
                mUname=uname.getText().toString();
                mPwd=pwd.getText().toString();
                String d="true";
                SharedPreferences prefs = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
                SharedPreferences.Editor editor = prefs.edit();
                editor.putString("Is_Login",d);
                editor.putString("EMP_ID",mUname);
                editor.putString("EMP_PWD",mPwd);
                editor.commit();
                if(!mUname.equalsIgnoreCase("") && !mPwd.equalsIgnoreCase(""))
                {
                    cd = new ConnectionDetector(getApplicationContext());
                    isInternetPresent = cd.isConnectingToInternet();
                    //Toast.makeText(MainActivity.this, isInternetPresent, Toast.LENGTH_LONG).show();
                    if(isInternetPresent)
                    {


                    try
                    {
                        validat_user(mUname,mPwd);
                        session.createLoginSession(mUname,mPwd);
                    }
                    catch(Exception e)
                    {
                        display("Network error.\nPlease check with your network settings.");
                        uname.setText("");
                        pwd.setText("");
                    }
                    }
                    else
                    {
                        display("No Internet Connection...");
                    }

                }
                else
                {
                    invalid.setText("Please enter the data");
                }
            }
        });
    }

        /*@Override
        protected void onResume() 
        {
              SharedPreferences sharedpreferences=getSharedPreferences(MyPREFERENCES, 
              Context.MODE_PRIVATE);
              if (sharedpreferences.contains(mUname))
              {
              if(sharedpreferences.contains(mPwd)){
                 Intent i = new Intent(this,Design_Activity.class);
                 startActivity(i);
              }
              }
              super.onResume();


    }*/
    public void display(String msg) 
    {
        Toast.makeText(MainActivity.this, msg, Toast.LENGTH_LONG).show();
    }


    private void validat_user(String stg1, String stg2)
    {
        db_select=stg1;
        WebServiceTask wst = new WebServiceTask(WebServiceTask.POST_TASK, this, "Login in progress...");

        wst.addNameValuePair("EMP_ID", stg1);
        wst.addNameValuePair("EMP_PWD", stg2);

        wst.execute(new String[] { SERVICE_URL });

    }
    @SuppressWarnings("deprecation")
    public void no_net()
    {
        display( "No Network Connection");
        final AlertDialog alertDialog = new AlertDialog.Builder(MainActivity.this).create();
        alertDialog.setTitle("No Internet Connection");
        alertDialog.setMessage("You don't have internet connection.\nElse please check the Internet Connection Settings.");
        //alertDialog.setIcon(R.drawable.error_info);
        alertDialog.setCancelable(false);
        alertDialog.setButton("Close", new DialogInterface.OnClickListener() 
        {
            public void onClick(DialogInterface dialog, int which)
            {   
                alertDialog.cancel();
                MainActivity.this.finish();
                System.exit(0);
            }
        });
        alertDialog.setButton2("Use Local DataBase", new DialogInterface.OnClickListener() 
        {
            public void onClick(DialogInterface dialog, int which)
            {
                display( "Accessing local DataBase.....");
                alertDialog.cancel();
            }
        });
        alertDialog.show();
    }

    private class WebServiceTask extends AsyncTask<String, Integer, String> {

        public static final int POST_TASK = 1;

        private static final String TAG = "WebServiceTask";

        // connection timeout, in milliseconds (waiting to connect)
        private static final int CONN_TIMEOUT =12000;

        // socket timeout, in milliseconds (waiting for data)
        private static final int SOCKET_TIMEOUT =12000;

        private int taskType = POST_TASK;
        private Context mContext = null;
        private String processMessage = "Processing...";

        private ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();

        private ProgressDialog pDlg = null;

        public WebServiceTask(int taskType, Context mContext, String processMessage) {

            this.taskType = taskType;
            this.mContext = mContext;
            this.processMessage = processMessage;
        }

        public void addNameValuePair(String name, String value) {

            params.add(new BasicNameValuePair(name, value));
        }

        @SuppressWarnings("deprecation")
        private void showProgressDialog() {

            pDlg = new ProgressDialog(mContext);
            pDlg.setMessage(processMessage);
            pDlg.setProgressDrawable(mContext.getWallpaper());
            pDlg.setProgressStyle(ProgressDialog.STYLE_SPINNER);
            pDlg.setCancelable(false);
            pDlg.show();

        }

        @Override
        protected void onPreExecute() {

            showProgressDialog();

        }

        protected String doInBackground(String... urls) {

            String url = urls[0].toString();
            String result = "";
            HttpResponse response = doResponse(url);
            if (response == null) {
                return result;
            } else {

                try {

                    result = inputStreamToString(response.getEntity().getContent());

                } catch (IllegalStateException e) {
                    Log.e(TAG, e.getLocalizedMessage(), e);

                } catch (IOException e) {
                    Log.e(TAG, e.getLocalizedMessage(), e);
                }
                catch(Exception e)
                {
                    Log.e(TAG, e.getLocalizedMessage(), e);
                }

            }

            return result;
        }

        @Override
        protected void onPostExecute(String response) {

            handleResponse(response);
            pDlg.dismiss();

        }

        // Establish connection and socket (data retrieval) timeouts
        private HttpParams getHttpParams() {

            HttpParams htpp = new BasicHttpParams();

            HttpConnectionParams.setConnectionTimeout(htpp, CONN_TIMEOUT);
            HttpConnectionParams.setSoTimeout(htpp, SOCKET_TIMEOUT);

            return htpp;
        }

        private HttpResponse doResponse(String url) {

            // Use our connection and data timeouts as parameters for our
            // DefaultHttpClient
            HttpClient httpclient = new DefaultHttpClient(getHttpParams());

            HttpResponse response = null;

            try {
                switch (taskType) {

                case POST_TASK:

                    HttpPost httppost= new HttpPost(url);
                    httppost.setEntity(new UrlEncodedFormEntity(params));
                    response = httpclient.execute(httppost);

                    break;
                }
            } 
            catch (Exception e) {
            //  display("Remote DataBase can not be connected.\nPlease check network connection.");

                Log.e(TAG, e.getLocalizedMessage(), e);
                return null;

            }

            return response;
        }

        private String inputStreamToString(InputStream is) {

            String line = "";
            StringBuilder total = new StringBuilder();

            // Wrap a BufferedReader around the InputStream
            BufferedReader rd = new BufferedReader(new InputStreamReader(is));

            try {
                // Read response until the end
                while ((line = rd.readLine()) != null) {
                    total.append(line);
                }
            } catch (IOException e) {
                Log.e(TAG, e.getLocalizedMessage(), e);
            }
            catch(Exception e)
            {
                Log.e(TAG, e.getLocalizedMessage(), e);
            }

            // Return full string
            return total.toString();
        }

    }
    public void handleResponse(String response) 

    {    
    //display("Response:"+response);
        if(!response.equalsIgnoreCase(""))
        {
            JSONObject jso;
            try {
                jso = new JSONObject(response);


                    String status = jso.getString("status");
                    int valid=jso.getInt("valid");
              //     display("Welcome : "+UName);
                 if(valid>0)
                 {
                    if( status.equalsIgnoreCase("") || status==null ||  status.equalsIgnoreCase("Failed"))
                    {
                        invalid.setText("Invalid password");
                        //reset();
                        pwd.setText("");
                    }
                    else
                    {
                        //session.createLoginSession(mUname,mPwd);
                        //display(status);
                        intObj=new Intent(MainActivity.this,Design_Activity.class);
                        startActivity(intObj);
                        MainActivity.this.finish();     
                    }

                 }
                 else
                 {
                     invalid.setText("Invalid userid");
                     uname.setText("");
                 }
                }
            catch (JSONException e1) {

                Log.e(TAG, e1.getLocalizedMessage(), e1);
            }
            catch(Exception e)
            {
                Log.e(TAG, e.getLocalizedMessage(), e);
            }


        }
        else
        {
            display("Could not able to reach Server!");
        }


    }
    public void reset()
    {


        pwd.setText("");
        uname.setText("");
    }

}
package com.example.employeeinclution;
导入java.io.BufferedReader;
导入java.io.IOException;
导入java.io.InputStream;
导入java.io.InputStreamReader;
导入java.util.ArrayList;
导入org.apache.http.HttpResponse;
导入org.apache.http.NameValuePair;
导入org.apache.http.client.HttpClient;
导入org.apache.http.client.entity.UrlEncodedFormEntity;
导入org.apache.http.client.methods.HttpPost;
导入org.apache.http.impl.client.DefaultHttpClient;
导入org.apache.http.message.BasicNameValuePair;
导入org.apache.http.params.BasicHttpParams;
导入org.apache.http.params.HttpConnectionParams;
导入org.apache.http.params.HttpParams;
导入org.json.JSONException;
导入org.json.JSONObject;
导入android.app.Activity;
导入android.app.AlertDialog;
导入android.app.ProgressDialog;
导入android.content.Context;
导入android.content.DialogInterface;
导入android.content.Intent;
导入android.content.SharedReferences;
导入android.nfc.Tag;
导入android.os.AsyncTask;
导入android.os.Bundle;
导入android.util.Log;
导入android.view.view;
导入android.widget.Button;
导入android.widget.EditText;
导入android.widget.TextView;
导入android.widget.Toast;
公共类MainActivity扩展了活动
{
公共编辑文本uname,pwd;
按钮btnlog1;
文本视图无效;
公共按钮BTNCENCEL1;
公共字符串db_select;
字符串名称;
字符串mPwd;
字符串温度;
意图输入北京;
意向=无效;
会话管理器会话;
布尔值isInternetPresent=false;
连接检测器cd;
专用字符串服务\u URL=”http://10.54.3.208:8080/";
私有最终字符串服务\u URL=Urlmanager.Address;
私有最终字符串TAG=“MainActivity”;
公共静态最终字符串PREFS\u NAME=“MyPrefsFile”;
公共静态最终字符串为\u Login=“Is\u Login”;
公共静态最终字符串MyPREFERENCES=“MyPREFERENCES”;
私有静态最终字符串是\u USER\u LOGIN=“IsUserLoggedIn”;
@凌驾
创建时受保护的void(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
MainActivity.this.setContentView(R.layout.activity_main);
uname=(EditText)findViewById(R.id.editText1);
pwd=(EditText)findViewById(R.id.editText2);
无效=(TextView)findViewById(R.id.textView3);
btnlog1=(按钮)findViewById(R.id.button1);
session=newsessionmanager(getApplicationContext());
btnlog1.setOnClickListener(新视图.OnClickListener()
{           
@凌驾
公共void onClick(视图v)
{
mUname=uname.getText().toString();
mPwd=pwd.getText().toString();
字符串d=“true”;
SharedReferences prefs=GetSharedReferences(prefs\u名称,Context.MODE\u PRIVATE);
SharedReferences.Editor=prefs.edit();
putString(“Is_Login”,d);
putString(“EMP_ID”,mUname);
编辑器.putString(“EMP_PWD”,mPwd);
commit();
if(!mUname.equalsIgnoreCase(“”)&!mPwd.equalsIgnoreCase(“”)
{
cd=新连接检测器(getApplicationContext());
isInternetPresent=cd.isConnectingToInternet();
//Toast.makeText(MainActivity.this,isInternetPresent,Toast.LENGTH_LONG.show();
如果(isInternetPresent)
{
尝试
{
验证用户(mUname、mPwd);
创建登录会话(mUname,mPwd);
}
捕获(例外e)
{
显示(“网络错误。\n请检查网络设置”);
uname.setText(“”);
pwd.setText(“”);
}
}
其他的
{
显示(“无互联网连接…”);
}
}
其他的
{
无效的.setText(“请输入数据”);
}
}
});
}
/*@凌驾
受保护的void onResume()
{
SharedReferences SharedReferences=GetSharedReferences(我的首选项,
上下文。模式(私人);
if(sharedReferences.contains(mUname))
{
if(SharedReferences.contains(mPwd)){
意向i=新意向(本设计活动类);
星触觉(i);
}
}
super.onResume();
}*/
公共无效显示(字符串消息)
{
Toast.makeText(MainActivity.this,msg,Toast.LENGTH_LONG.show();
}
私有void验证用户(字符串stg1、字符串stg2)
{
db_select=stg1;
WebServiceTask wst=新的WebServiceTask(WebServiceTask.POST_任务,这是“正在登录…”);