gpt4 book ai didi

java - 在Android中用java代码访问mysql

转载 作者:行者123 更新时间:2023-11-29 23:23:52 25 4
gpt4 key购买 nike

在 Mysql 表中我有数据库:-

mysql> use student
mysql> select * from ari;
+----+-------+
| id | name |
+----+-------+
| 22 | Sandy |
+----+-------+

我已经在我的电脑上安装了jetty和mysql,端口是:--

http://localhost(172.0.0.1):8080/
http://localhost(172.0.0.1):3306/

这是我的java代码:--(MainActivity.java)

  public class MainActivity extends Activity {
private static final String url = "jdbc:mysql://localhost:3306/student";
private static final String user = "root";
private static final String pass = "root";
/** 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.textView1);

try {

Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection(url, user, pass);
String result = "Database connection success\n";
Statement st = con.createStatement();
ResultSet rs = st.executeQuery("select * from ari");
ResultSetMetaData rsmd = rs.getMetaData();

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

tv.setText(result);
}
catch(Exception e) {

e.printStackTrace();
tv.setText(e.toString());
}
}
}

activity_main.xml 是:--

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin" >
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
</RelativeLayout>

在我的项目中,我还添加了mysql-connector-java-5.1.34.jar

但是当我运行时,它在我的 Android 设备(手机)中显示错误:--

   com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: 
Could not create connection to database server

谁能告诉我问题出在哪里???????????????

最佳答案

如果您在手机中运行应用程序,显然它需要连接到您的 PC 的 IP 地址。不是本地主机。并且您的电脑和手机需要处于同一网络。

例如jdbc:mysql://your-pc-ip-address:3306/student

关于java - 在Android中用java代码访问mysql,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27098516/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com