Home >Database >Mysql Tutorial >What to do if Android cannot connect to mysql
Solution to the problem that Android cannot connect to mysql: First, customize the listening event in Activivty; then open up a child thread in the custom listening event; finally, change the definition of coonection to "DriverManager.getConnection(... )".
Recommendation: "mysql video tutorial"
Android Studio connects to MySQL: Problem solved: The virtual machine cannot connect to the local SQL, coon is always empty
Connect to the database in a child thread
First customize the listening event in Activivty
//写在Activity中 private Button mBtn; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); SetListener();//自定义监听事件 }
Open a child thread in the custom listening event , pay attention to the last .start()
private void SetListener() { mBtnadmin.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { new Thread(new Runnable() { @Override public void run() { Connection conn=null;//创建连接 Statement stmt=null;//用以执行SQL语句 try{ //注册驱动 Class.forName("com.mysql.jdbc.Driver"); //数据库的执行语句 String sql="insert into demo values(6666,6666)"; //获取connection对象,这里使用localhost如果无法成功,则改成10.0.2.2,这是虚拟机上电脑的地址,注意是虚拟机,用于虚拟机的测试 conn=DriverManager.getConnection("jdbc:mysql://10.0.2.2:3306/logindata","root","666666"); stmt=conn.createStatement(); stmt.executeUpdate(sql); } }catch (Exception e) { e.printStackTrace(); }finally { stmt.close(); conn.close(); // JDBCUtils .Close(stmt,conn); } } }).start(); } }); }
Because I have been using a virtual machine for testing, the definition of coonection has always been
conn= DriverManager.getConnection("jdbc:mysql://localhost/logindata","root","666666");
Every time the connection result is reported: coon=null, Finally, multiple debugging parties discovered this problem. The IP address of the computer corresponding to the virtual machine should be 10.0.2.2. That is, changing the definition of coonection to
conn= DriverManager.getConnection("jdbc:mysql://10.0.2.2:3306/logindata","root","666666");
was successful! I was always worried that it was a code problem, so I didn’t try to connect to MySQL on the server. Now I can try it!
The above is the detailed content of What to do if Android cannot connect to mysql. For more information, please follow other related articles on the PHP Chinese website!