我试图从Java中插入数据到mysql表中,但数据不会出现在表中[关闭]

oogrdqng  于 2023-05-05  发布在  Java
关注(0)|答案(2)|浏览(139)

**关闭。**此题需要debugging details。目前不接受答复。

编辑问题以包含desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem。这将帮助其他人回答这个问题。
2天前关闭。
Improve this question
下面是我的代码:

public static void insertData(stockData stock) throws Exception{
        Connection con;
        try {
            con = getConnection();
            String sql = "INSERT INTO stocks (id, ticker, price, percentChange, volume, net income) VALUES (?, ?, ?, ?, ?, ?);";
            PreparedStatement insert = con.prepareStatement(sql);

            insert.setInt(1, 0);
            insert.setString(2, stock.Ticker);
            insert.setString(3, stock.Price);
            insert.setString(4, stock.PercentChange);
            insert.setString(5, stock.Volume);
            insert.setString(6, stock.NetIncomeCurrent);

            insert.executeUpdate();

        } catch (SQLException e){
            System.out.println("ERROR");
            throw new SQLException();
        }
        con.close();
}

我相信问题出在insert.executeUpdate();陈述。
我尝试了insert.execute();
该表确实存在,但所有值均为null

4dbbbstv

4dbbbstv1#

这里我可能漏掉了一些东西,但是带空格的net income通常不是有效的列名,除非您专门以这种方式创建它。您可以尝试将其 Package 在反引号中,看看它是否有效。该列的名称中是否有空格?
一些参考:How to create column name with space?

String sql = "INSERT INTO stocks (id, ticker, price, percentChange, volume, `net income`) VALUES (?, ?, ?, ?, ?, ?);";
qxsslcnc

qxsslcnc2#

我假设您的数据库连接示例为con.getAutoCommit()返回false
如果是这样,调用Connection::commit应该可以完成这项工作:

public static void insertData( stockData stock ) throws SQLException
{
  try( final var connection = getConnection() )
  {
    assert !connection.getAutoCommit() : "Connection uses autocommit";
    final var sql = 
      """
      INSERT INTO stocks 
      (id, ticker, price, percentChange, volume, net_income) 
      VALUES (?, ?, ?, ?, ?, ?);""";
    try( final var insert = connection.prepareStatement( sql ) )
    {
      insert.setInt( 1, 0 );
      insert.setString( 2, stock.Ticker );
      insert.setString( 3, stock.Price );
      insert.setString( 4, stock.PercentChange );
      insert.setString( 5, stock.Volume );
      insert.setString( 6, stock.NetIncomeCurrent );

      insert.executeUpdate();

      connection.commit();    // <<<<<<
    }
    catch( final SQLException e )
    {
      connection.rollback();  // <<<<<<
      throw e;
    }
  } 
  catch( final SQLException e )
  {
    System.out.println( "ERROR" );
    throw e;
  }
}

当然我们需要讨论错误处理。。特别是因为如果连接在没有提交的情况下关闭,则回滚是隐含的。
或者,您可以在获得连接后通过调用connection.setAutoCommit( true )强制自动提交;在这种情况下,第一个catch块被废弃。

相关问题