Android:com.mysql.jdbc.exceptions.jdbc4.communicationsexception通信链接失败

时间:2013-01-07 00:16:18

标签: android jdbc

我有正确的IP:端口,所以我不知道问题出在哪里,因为communicationsexception来自mysql数据库的url:port。

package com.bbb.aaa;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class MainActivity extends Activity {

private static final String url = "jdbc:mysql://uk1.khttp.net:2083/thedatabase"; // uk1.khttp.net == 95.154.195.28
private static final String user = "theusername";
private static final String pass = "thepassword";

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    System.out.println("About to try instantiating driver");


TextView tv = (TextView)this.findViewById(R.id.text_view);
try {
    Class.forName("com.mysql.jdbc.Driver");
    System.out.print("success");
    Connection con = DriverManager.getConnection(url, user, pass);
    String result = "Database connection success\n";
    System.out.print("success2");
    Statement st = con.createStatement();
    ResultSet rs = st.executeQuery("SELECT * FROM testingregistration");
    System.out.print("success3");
    ResultSetMetaData rsmd = rs.getMetaData();

    while(rs.next()) {
        result += rsmd.getColumnName(1) + ": " + rs.getInt(1) + "\n";
        result += rsmd.getColumnName(2) + ": " + rs.getString(2) + "\n";
        result += rsmd.getColumnName(3) + ": " + rs.getString(3) + "\n";
    }
    tv.setText(result);

    tv.setText("Driver instantiated");
    } catch (ClassNotFoundException e) {
    // TODO Auto-generated catch block

    tv.setText(".....Class com.mysql.jdbc.Driver not found!");
    e.printStackTrace();
    } catch (SQLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        tv.setText(e.toString());
    }

}

}

ERROR LOG: The last packet sent successfuly to the server was 0 milliseconds ago. The driver has not recieved any packets from the server

控制台读取并打印“成功”,但之后它崩溃,因此它不会打印“success2”,这意味着问题出在连接处。

我试着在互联网上搜索这个问题,但他们说的只是你的ip:端口和数据库应该是正确的但对我来说这似乎是正确的,因为我可以使用该URL和端口的登录名和密码详细信息登录到mysql然后从那里我点击phpMyAdmin和im在数据库中。

提前致谢

1 个答案:

答案 0 :(得分:1)

使用 AsyncTask 。你的try catch块代码写在asynctask的doInBackground方法中。试试吧。