gpt4 book ai didi

java - 使用 JDBC 将 android 与数据库连接

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

我试图连接和应用免费服务器,尝试使用网络服务但根本无法做到,所以现在我尝试使用 jdbc 来做到这一点:

代码:

@Override
protected void onCreate(Bundle savedInstanceState) {



super.onCreate(savedInstanceState);
setContentView(R.layout.login);
getActionBar().hide();

new Con().execute();}

private class Con extends AsyncTask<Void, Void, Void> {

// JDBC driver name and database URL
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://31.170.165.253/u802222393_gp";

// Database credentials
static final String USER = "u802222393_books";
static final String PASS = "aboasendar";

@Override
protected Void doInBackground(Void... params) {
Connection conn = null;
Statement stmt = null;

try {
// STEP 2: Register JDBC driver
Class.forName(JDBC_DRIVER).newInstance();




// STEP 3: Open a connection
System.out.println("Connecting to database...");
conn = DriverManager.getConnection(DB_URL, USER, PASS);

// STEP 4: Execute a query
System.out.println("Creating statement...");
stmt = conn.createStatement();
String sql= "SELECT id, first, last, age FROM test";
ResultSet rs = stmt.executeQuery(sql);

// STEP 5: Extract data from result set
while (rs.next()) {
// Retrieve by column name
int id = rs.getInt("id");
int age = rs.getInt("age");
String first = rs.getString("first");
String last = rs.getString("last");

// Display values
System.out.print("ID: " + id);
System.out.print(", Age: " + age);
System.out.print(", First: " + first);
System.out.println(", Last: " + last);
}
// STEP 6: Clean-up environment
rs.close();
stmt.close();
conn.close();
} catch (SQLException se) {
// Handle errors for JDBC
se.printStackTrace();
} catch (Exception e) {
// Handle errors for Class.forName
e.printStackTrace();
} finally {
// finally block used to close resources
try {
if (stmt != null)
stmt.close();
} catch (SQLException se2) {
}// nothing we can do
catch (java.sql.SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
if (conn != null)
conn.close();
} catch (SQLException se) {
se.printStackTrace();
}// end finally try
catch (java.sql.SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}// end try
System.out.println("Goodbye!");

return null;
}

它总是在我搜索了很多但没有找到关于我应该如何编写 URL 的答案的 URL 上给出一个异常(exception)

日志:enter image description here

最佳答案

您可以使用本地主机(将您的计算机用作服务器)并随心所欲地工作要在 Android 中使用 JDBC,您会在这里找到很好的指南, http://www.vogella.com/tutorials/MySQLJava/article.html

如果你想从 jdbc 开始,你可以从这个教程开始 http://www.tutorialspoint.com/jdbc/jdbc-introduction.htm

如有任何问题,欢迎留言谢谢

关于java - 使用 JDBC 将 android 与数据库连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28108898/

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