列表返回的 JAVA JDBC 问题

Posted

技术标签:

【中文标题】列表返回的 JAVA JDBC 问题【英文标题】:JAVA JDBC issues with List Return 【发布时间】:2018-07-02 18:19:20 【问题描述】:

长期潜伏者。我一直在使用 Java 尝试执行我拥有的这个 JDBC SQL 语句,并且有时可以将结果运行类作为静态 void。当我尝试将结果集放入列表并返回时,我会在底部附加错误日志。如果我没有正确发布某些内容,我会事先道歉。奇怪的是我错过了一些东西,但似乎无法让我的眼睛注意到它。

提前致谢

附:温柔点,我是第一次。

珠光宝气

///////////////调用SQL事件的主Activity//////////////////// //

protected void onCreate(Bundle savedInstanceState) 
    int SDK_INT = android.os.Build.VERSION.SDK_INT;
    if (SDK_INT > 8)
    
        StrictMode.ThreadPolicy policy = new 
StrictMode.ThreadPolicy.Builder()
                .permitAll().build();
        StrictMode.setThreadPolicy(policy);
        //your codes here

    
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);


    SQLEvent EVENTS = new SQLEvent();
    List<List<String>> EventString = EVENTS.main();
    System.out.println("EVENT RESULTS: " + EventString);

///////////////SQL事件////////////////////////////////////////////////////////// p>

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class SQLEvent

static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://***.***.***.***:3306/DB_NAME?useSSL=false&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC";

//  Database credentials
static final String USER = "*******";
static final String PASS = "*******";






public List <List<String>>  main() 
    ResultSet rs = null;
    Connection conn = null;
    java.sql.PreparedStatement stmt = null;
    List<List<String>> result = new ArrayList<>();

    try 
        //STEP 2: Register JDBC driver
        Class.forName("com.mysql.cj.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...");
        String sql = "SELECT * FROM events WHERE LOC= ?";

        stmt = conn.prepareStatement(sql);

        //Bind values into the parameters.
        stmt.setString(1, "matts office");  // This would set age

        // Let us update age of the record with ID = 102;
        //int rows = stmt.executeUpdate();
        //  System.out.println("Rows impacted : " + rows );

        // Let us select all the records and display them.
        // sql = "SELECT id, first, last, age FROM Employees";
        // stmt.setInt(1, 1001);
        rs = stmt.executeQuery();
        int numcols = rs.getMetaData().getColumnCount();


        //STEP 5: Extract data from result set
        while (rs.next()) 
            List<String> row = new ArrayList<>(numcols); // new list per row
            int i = 1;
            while (i <= numcols)   // don't skip the last column, use <=
                row.add(rs.getString(i++));
            
            result.add(row); // add it to the result

            //Retrieve by column name
            int id = rs.getInt("id");
            String LOC = rs.getString("LOC");
            String EventName = rs.getString("EventName");
            String EventDesc = rs.getString("EventDesc");
            String Closed = rs.getString("Closed");
            String TimeStart = rs.getString("TimeStart");
            String TimeEnd = rs.getString("TimeEnd");


            //Display values
            System.out.print("ID: " + id);
            System.out.print(", Location: " + LOC);
            System.out.print(", Event Name: " + EventName);
            System.out.println(", Event Description: " + EventDesc);
            System.out.println(", Closed: " + Closed);
            System.out.println(", Time Start: " + TimeStart);
            System.out.println(", Time End: " + TimeEnd);

        
        //STEP 6: Clean-up environment
        if (!rs.next()) 

         else 
            //  MainActivity MA = new MainActivity();
            // MA.NotificationEvent();
        

        stmt.close();
        conn.close();
        System.out.println("Result Set: " + result);
        rs.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
        try 
            if (conn != null)
                conn.close();
         catch (SQLException se) 
            se.printStackTrace();
        //end finally try
    //end try
    System.out.println("Goodbye!");


    return result;

//////////////////错误日志///////////////////// ///////////////

07-02 18:02:43.286 11991-11991/com.internalpositioning.find3.find3app E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.internalpositioning.find3.find3app, PID: 11991
java.lang.BootstrapMethodError: Exception from call site #145 bootstrap method
    at com.mysql.cj.conf.ConnectionUrl.buildConnectionStringCacheKey(ConnectionUrl.java:236)
    at com.mysql.cj.conf.ConnectionUrl.getConnectionUrlInstance(ConnectionUrl.java:167)
    at com.mysql.cj.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:201)
    at java.sql.DriverManager.getConnection(DriverManager.java:569)
    at java.sql.DriverManager.getConnection(DriverManager.java:219)
    at com.internalpositioning.find3.find3app.SQLEvent.main(SQLEvent.java:45)
    at com.internalpositioning.find3.find3app.MainActivity.onCreate(MainActivity.java:144)
    at android.app.Activity.performCreate(Activity.java:7009)
    at android.app.Activity.performCreate(Activity.java:7000)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1214)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2731)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2856)
    at android.app.ActivityThread.-wrap11(Unknown Source:0)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1589)
    at android.os.Handler.dispatchMessage(Handler.java:106)
    at android.os.Looper.loop(Looper.java:164)
    at android.app.ActivityThread.main(ActivityThread.java:6494)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
 Caused by: java.lang.NoClassDefFoundError: Invalid descriptor: VIIIIIIIIII.
    at com.mysql.cj.conf.ConnectionUrl.buildConnectionStringCacheKey(ConnectionUrl.java:236) 
    at com.mysql.cj.conf.ConnectionUrl.getConnectionUrlInstance(ConnectionUrl.java:167) 
    at com.mysql.cj.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:201) 
    at java.sql.DriverManager.getConnection(DriverManager.java:569) 
    at java.sql.DriverManager.getConnection(DriverManager.java:219) 
    at com.internalpositioning.find3.find3app.SQLEvent.main(SQLEvent.java:45) 
    at com.internalpositioning.find3.find3app.MainActivity.onCreate(MainActivity.java:144) 
    at android.app.Activity.performCreate(Activity.java:7009) 
    at android.app.Activity.performCreate(Activity.java:7000) 
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1214) 
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2731) 
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2856) 
    at android.app.ActivityThread.-wrap11(Unknown Source:0) 
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1589) 
    at android.os.Handler.dispatchMessage(Handler.java:106) 
    at android.os.Looper.loop(Looper.java:164) 
    at android.app.ActivityThread.main(ActivityThread.java:6494) 
    at java.lang.reflect.Method.invoke(Native Method) 
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438) 
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807) 

【问题讨论】:

【参考方案1】:

我想您的 MySQL 驱动程序版本不适用于 Android。看起来,它在Collectors.joining 上失败了。这是在 Java 8 中添加的。

另外,在我看来,直接从 Android 连接到数据库很奇怪。据我所知,通常移动应用程序会向有权访问数据库的后端层发出一些请求(通常是 REST)。

【讨论】:

感谢您的帮助!我会调查的。

以上是关于列表返回的 JAVA JDBC 问题的主要内容,如果未能解决你的问题,请参考以下文章

如何使用 java JDBC 获取 MySql 的数据库“模式”名称列表

mysql原始jdbc查询例子,返回数据列表

使用 Java 返回 OBIEE 主题区域和受尊重的表

DAO 层可以返回一个 JDBC ResultSet (Java)

为啥 JDBC 代码在 Java 中可以工作,但在 Android 中返回 null?

Spring JDBC:返回 0 或 1 行