如何使用JDBC驱动程序在Android中连接MySql

时间:2017-05-20 07:03:05

标签: java android mysql jdbc

我在使用JDBC驱动程序连接到MySql数据库时发出错误消息。

这里的源代码,

错误消息是

通讯链接失败。 最后一个数据包发送到服务器是0毫秒前

    public class MainActivity extends Activity {
    private static final String url = "jdbc:mysql://192.168.0.105:8081/onlineexam";
        private static final String user = "root";
        private static final String pass = "";

        /** Called when the activity is first created. */
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            testDB();
        }

        public void testDB() {
            TextView tv = (TextView)this.findViewById(R.id.exceptions);
            try {
                Class.forName("com.mysql.jdbc.Driver");
                Connection con = DriverManager.getConnection(url, user, pass);
                /* System.out.println("Database connection success"); */

                String result = "Database connection success\n";
                Statement st = con.createStatement();
                ResultSet rs = st.executeQuery("select * from ft_users");
                ResultSetMetaData rsmd = rs.getMetaData();

                while(rs.next()) {
                    result += rsmd.getColumnName(0) + ": " + rs.getInt(0) + "\n";
                    result += rsmd.getColumnName(1) + ": " + rs.getString(1) + "\n";
                    result += rsmd.getColumnName(2) + ": " + rs.getString(2) + "\n";
                }
                tv.setText(result);
            }
            catch(Exception e) {
                e.printStackTrace();
                tv.setText(e.toString());
            }

        }
    }

0 个答案:

没有答案