Android studio连接到远程数据库

时间:2018-04-14 12:29:27

标签: java sql android-studio

我正在尝试将Android Studio应用程序连接到托管在“hostbuddy”上的远程服务器。这是代码(当发送数据时错误是“连接出错2”)让我猜测DB_URL有问题。我试过在很多方面改变网址,没有用。如果它有帮助我也可以发布logcat。

编辑:我修好了,我忘了为MySQl连接器添加模块,现在就像魅力一样^ _ ^

package com.example.battl.qr2;

import android.content.Intent;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import org.w3c.dom.Text;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;

public class Register extends AppCompatActivity {

    TextView textView;
    Button button;
    EditText editText;
    private static final String DB_URL= "jdbc:mysql://mysql6002.site4now.net/db_a37d85_mydb:3306";
    private static final String USER = "X";
    private static final String PASS = "X";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);

        textView=(TextView) findViewById(R.id.textView);
        editText=(EditText) findViewById(R.id.editText);
    }

    public void btnConn(View view)
    {
        Send objsend = new Send();
        objsend.execute("");
    }

    private class Send extends AsyncTask<String,String,String>
    {
        String msg = "";
        String text = editText.getText().toString();

        @Override
        protected  void onPreExecute() {textView.setText("Please Wait Inserting");}

        @Override
        protected String doInBackground(String... strings)
        {
            try
            {
                Class.forName("com.mysql.jdbc.Driver");
                Connection conn = DriverManager.getConnection(DB_URL,USER,PASS);

                if(conn == null) {
                    msg="Connection goes wrong";
                } else {
                    String query = "INSERT INTO ex (col1) VALUES ('"+text+"') ";
                    Statement stmt = conn.createStatement();
                    stmt.executeUpdate(query);
                    msg = "Inserted successfully";
                }

                conn.close();
            }
            catch (Exception e)
            {
                msg="Connection goes wrong 2";
                e.printStackTrace();
            }

            return msg;
        }

        @Override
        protected void onPostExecute(String msg) {textView.setText(msg);}
    }
}

0 个答案:

没有答案