mysql—创建一个后端JavaRESTfulAPI,它将与存储在云上的数据库通信

vof42yt1  于 2021-06-18  发布在  Mysql
关注(0)|答案(1)|浏览(415)

我目前正在学习javaee,我被要求开发一个后端restfuljavaapi,它将与存储在云解决方案(ibmbluemix)上的数据库通信。
我目前使用eclipsephoton作为ide,我不是计算机上的管理员用户。
我被要求用ibmwas-liberty-server-pluginforeclipse测试我的代码,但是我在设置服务器时遇到了一些问题。我想我可能还不明白这个插件是怎么工作的,不能让它按我所希望的那样工作。
问题是,我无法访问存储在该服务器上的数据库,无论是使用我的api还是管理中心(甚至无法登录管理中心)。
下面是我在这个网站上使用(修改)的java代码

package connection;

//STEP 1. Import required packages
import java.sql.*;

public class FirstExample {
 // JDBC driver name and database URL
 static final String JDBC_DRIVER = "com.mysql.cj.jdbc.Driver";  
 static final String DB_URL = "jdbc:mysql://localhost:3306/ibm/api/validator/dataSource/SAMPLEDB";
 //  Database credentials
 static final String USER = "admin";
 static final String PASS = "admin";

 public static void main(String[] args) {
 Connection conn = null;
 Statement stmt = null;
 try{
    //STEP 2: Register JDBC driver
    Class.forName(JDBC_DRIVER);

    //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;
    sql = "SELECT * FROM *";
    ResultSet rs = stmt.executeQuery(sql);

    //STEP 5: Extract data from result set
    while(rs.next()){
       //Retrieve by column name

       String data = rs.getString("last");
       //Display values
       System.out.println("Data Retreived " + data);
    }
    //STEP 6: Clean-up environment
    rs.close();
    stmt.close();
    conn.close();
 }catch(SQLException se){
    //Handle errors for JDBC
     System.out.println("\nJDBC ERROR ! \n");
    se.printStackTrace();
 }catch(Exception e){
    //Handle errors for Class.forName
     System.out.println("\nClass.forName ERROR ! \n");
    e.printStackTrace();
 }finally{
    //finally block used to close resources
    try{
       if(stmt!=null)
          stmt.close();
    }catch(SQLException se2){
        System.out.println("\nSQL ERROR ! NOTHING TO DO \n");
    }// nothing we can do
    try{
       if(conn!=null)
          conn.close();
    }catch(SQLException se){
        System.out.println("\nJDBC ERROR ! MAYBE SOMETHING TO DO \n");
       se.printStackTrace();
    }//end finally try
 }//end try
 System.out.println("\nGoodbye!");
}//end main
}//end FirstExample

至于my server.xml,下面是更新的代码:

<server description="Liberty beta">

    <featureManager>
        <feature>webProfile-8.0</feature>
        <feature>adminCenter-1.0</feature>
        <feature>restConnector-2.0</feature>
        <feature>transportSecurity-1.0</feature>
        <feature>logstashCollector-1.1</feature>
        <feature>validator-1.0</feature>

        <feature>mpConfig-1.3</feature>
        <feature>mpFaultTolerance-1.1</feature>
        <feature>mpHealth-1.0</feature>
        <feature>mpJwt-1.0</feature>
        <feature>mpMetrics-1.1</feature>
        <feature>mpOpenAPI-1.0</feature>
        <feature>mpOpenTracing-1.0</feature>
        <feature>mpRestClient-1.0</feature>

        <feature>localConnector-1.0</feature>
        <feature>jdbc-4.2</feature>
    </featureManager>

    <httpEndpoint   id="defaultHttpEndpoint"
                    host="*"
                    httpPort="9080"
                    httpsPort="9443" />

    <applicationManager autoExpand="true"/>

    <keyStore   id="defaultKeyStore"
                password="Liberty" />

    <basicRegistry id="userReg">
        <user   password="admin"
                name="admin"
                id="admin"></user>
    </basicRegistry>

    <administrator-role>
        <user>admin</user>
    </administrator-role>

    <remoteFileAccess>
        <writeDir>${server.config.dir}</writeDir>
    </remoteFileAccess>

    <dataSource id="DefaultDataSource" jndiName="jdbc/mySQL">
        <jdbcDriver libraryRef="MySQLLib" />
        <properties.microsoft.sqlserver databaseName="SAMPLEDB" serverName="localhost" portNumber="3306" user="admin" password="admin"/>
        <connectionManager></connectionManager>
    </dataSource>
    <library id="MySQLLib">
        <file name="C:/PUBLIC/tools/mysql-connector-java-8.0.12/mysql-connector-java-8.0.12/mysql-connector-java-8.0.12.jar" />
    </library>    

</server>

我现在的问题是,我似乎无法与我的服务器进行通信。
以下是控制台错误:

Connecting to database...

JDBC ERROR ! 

Goodbye!
com.mysql.cj.jdbc.exceptions.CommunicationsException: Communications link failure

The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
    at com.mysql.cj.jdbc.exceptions.SQLError.createCommunicationsException(SQLError.java:174)
    at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:64)
    at com.mysql.cj.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:832)
    at com.mysql.cj.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:456)
    at com.mysql.cj.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:240)
    at com.mysql.cj.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:207)
    at java.sql.DriverManager.getConnection(DriverManager.java:664)
    at java.sql.DriverManager.getConnection(DriverManager.java:247)
    at connection.FirstExample.main(FirstExample.java:23)
Caused by: com.mysql.cj.exceptions.CJCommunicationsException: Communications link failure

The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
    at com.mysql.cj.exceptions.ExceptionFactory.createException(ExceptionFactory.java:61)
    at com.mysql.cj.exceptions.ExceptionFactory.createException(ExceptionFactory.java:105)
    at com.mysql.cj.exceptions.ExceptionFactory.createException(ExceptionFactory.java:151)
    at com.mysql.cj.exceptions.ExceptionFactory.createCommunicationsException(ExceptionFactory.java:167)
    at com.mysql.cj.protocol.a.NativeSocketConnection.connect(NativeSocketConnection.java:91)
    at com.mysql.cj.NativeSession.connect(NativeSession.java:152)
    at com.mysql.cj.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:952)
    at com.mysql.cj.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:822)
    ... 6 more
Caused by: java.net.ConnectException: Connection refused: connect
    at java.net.DualStackPlainSocketImpl.connect0(Native Method)
    at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:79)
    at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350)
    at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206)
    at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188)
    at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172)
    at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
    at java.net.Socket.connect(Socket.java:589)
    at com.mysql.cj.protocol.StandardSocketFactory.connect(StandardSocketFactory.java:173)
    at com.mysql.cj.protocol.a.NativeSocketConnection.connect(NativeSocketConnection.java:65)
    ... 9 more
9gm1akwq

9gm1akwq1#

作为一个初学者,我试着盲目地遵循网上找到的教程,并没有想过我实际上在做什么。
我不明白,在liberty中设置数据源并不是建立一个数据库,liberty并不像用你想要的服务建立一个虚拟机。由于缺乏信息、指导和严谨性,我认为在创建数据源时,liberty服务器实际上运行的是mysql服务器。事实上(如果我错了请纠正我)这部分代码,

<dataSource id="DefaultDataSource" jndiName="jdbc/mySQL">
    <jdbcDriver libraryRef="MySQLLib" />
    <properties.microsoft.sqlserver databaseName="SAMPLEDB"
                                    serverName="localhost"
                                    portNumber="3306"
                                    user="admin"
                                    password="admin"/>
    <connectionManager></connectionManager>
</dataSource>

<library id="MySQLLib">
    <file name="C:/PUBLIC/tools/mysql-connector-java-8.0.12/mysql-connector-java-8.0.12/mysql-connector-java-8.0.12.jar" />
</library>

是为了在服务器上设置服务,并提供足够的驱动程序来连接到远程数据库。在这个场景中,我使用mysql驱动程序设置了一个数据源。
当我运行本地mysql服务器时,我能够通过java应用程序进行通信和发送查询。
感谢那些花时间阅读这篇文章并试图帮助我的人。

相关问题