mysql链接失败 驱动_Android连接MySQL问题,驱动加载成功,连接却失败

import android.support.v7.app.AppCompatActivity;

import android.os.Bundle;

import android.widget.TextView;

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.SQLException;

public class MainActivity extends AppCompatActivity {

private TextView textView,textTwo;

private final static String URL = "jdbc:mysql://localhost:3306/librarydb";

static String rootName = "root";

static String PWD = "1997831";

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

textView= (TextView) findViewById(R.id.textView);

textTwo= (TextView) findViewById(R.id.textTwo);

try {

Class.forName("com.mysql.jdbc.Driver");

textView.setText("驱动加载成功");

} catch (ClassNotFoundException e) {

textView.setText("找不到驱动程序类 ,加载驱动失败!");

e.printStackTrace();

}

new Thread(new Runnable() {

@Override

public void run() {

try {

Connection conn= conn = (Connection) DriverManager.getConnection(URL,rootName,PWD);

textTwo.setText("数据库连接成功!");

} catch (SQLException e) {

textTwo.setText("数据库连接失败!");

e.printStackTrace();

}

}

}).start();

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要在Android应用程序中连接MySQL数据库,可以使用以下步骤: 1. 在MySQL服务器上创建数据库和表,并添加数据。 2. 在Android应用程序中添加连接MySQL数据库的驱动程序(例如,MySQL Connector/J)。 3. 在Android应用程序中创建一个线程(如AsyncTask),并在线程中编写代码以连接MySQL数据库,并执行SQL查询。 4. 在Android应用程序中解析MySQL数据库返回的结果,并将结果显示在UI上。 下面是一个简单的示例,演示如何在Android应用程序中连接MySQL数据库: ```java // 导入MySQL Connector/J库 import java.sql.*; // 定义MySQL数据连接参数 String url = "jdbc:mysql://localhost:3306/test"; String user = "root"; String password = "password"; // 在线程中连接MySQL数据库 new AsyncTask<Void, Void, Void>() { @Override protected Void doInBackground(Void... params) { try { // 加载MySQL驱动程序 Class.forName("com.mysql.jdbc.Driver"); // 创建MySQL连接 Connection con = DriverManager.getConnection(url, user, password); // 创建SQL查询 Statement stmt = con.createStatement(); ResultSet rs = stmt.executeQuery("SELECT * FROM users"); // 解析查询结果 while (rs.next()) { String name = rs.getString("name"); int age = rs.getInt("age"); // TODO: 显示查询结果 } // 关闭数据连接 rs.close(); stmt.close(); con.close(); } catch (Exception e) { // TODO: 处理异常 } return null; } }.execute(); ``` 需要注意的是,在实际应用中,需要考虑到数据安全和性能等问题,例如,使用SSL加密连接、防止SQL注入等。同时,还需要考虑到在移动网络环境下,数据连接的稳定性和性能问题
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值