java - PreparedStatementexecute() 不影响数据库

标签 java mysql database jdbc

我在使用 jdbc 将数据插入 mysql 数据库时遇到问题。 当向数据库添加新用户时,我会获得一个新连接,创建一个准备好的语句并执行查询。但是,数据库中未显示任何结果。

例如,假设我使用 MySql 查询浏览器在数据库中手动添加一个新用户。

  • 我添加一个新用户 --> name = Stefano,pin = 1010
  • 生成自动递增 id:id = 1。

假设我决定以编程方式添加新用户:

  • 我调用方法 addUser(String username, int pin) --> addUser("pippo", 7636);
  • 没有发生错误
  • 我打开 MySql 查询浏览器,但未添加任何用户。

最后我手动添加一个新用户: 名称 = pluto ,引脚 = 3434。

现在我的表格结果是:

<表类=“s-表”> <标题> id 姓名 别针 <正文> 1 斯特凡诺 1010 3 冥王星 3434

id=2不见了。所以pippo已添加,但看不到。

出了什么问题?

这里我的java代码被简化了:

package simpleexample;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;

public class SimpleExample {

public static void addUser(String username, int pin) {
    
    Connection conn = null;
    PreparedStatement preparedStmt = null;
    String insertSQL = "insert into users(name, pin) values (?, ?)";

    try {

        conn = DBConnectionPool.getConnection();

        preparedStmt = conn.prepareStatement(insertSQL);
        preparedStmt.setString(1, username);
        preparedStmt.setInt(2, pin);
        preparedStmt.execute();

    } catch (SQLException ex) {
        Logger.getLogger(SimpleExample.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
        if (conn != null) {
            DBConnectionPool.releaseConnection(conn);
        }
    }
}

public static void main(String[] args) {
    
    addUser("pippo", 7636);
}
}

这里是 DBConnectionPool 类:

package simpleexample;

import java.util.*;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.*;

/**
  * This class simulates a db connection pool
  */
 public class DBConnectionPool {

/*
 * This code prepare the db connection pool. In particular, it creates the
 * free connections queue and defines the db properties.
 */
static {
    freeDbConnections = new ArrayList<Connection>();
    try {
        DBConnectionPool.loadDbProperties();
        DBConnectionPool.loadDbDriver();
    } catch (ClassNotFoundException e) {
        System.out.println("DB DRIVER NOT FOUND!");
        System.exit(1);
    } catch (IOException e) {
        System.out.println("DB CONNECTION POOL ERROR!");
        System.exit(2);
    }
}

/**
 * The db properties (driver, url, login, and password)
 */
private static Properties dbProperties;

/**
 * The free connection queue
 */
private static List<Connection> freeDbConnections;

/**
 * Returns a free db connection accessing to the free db connection queue.
 * If the queue is empty a new db connection will be created.
 *
 * @return A db connection
 * @throws SQLException
 */
public static synchronized Connection getConnection() throws SQLException {
    Connection connection;

    if (!freeDbConnections.isEmpty()) {
        // Extract a connection from the free db connection queue
        connection = freeDbConnections.get(0);
        DBConnectionPool.freeDbConnections.remove(0);

        try {
            // If the connection is not valid, a new connection will be
            // analyzed
            if (connection.isClosed()) {
                connection = DBConnectionPool.getConnection();
            }
        } catch (SQLException e) {
            connection = DBConnectionPool.getConnection();
        }
    } else // The free db connection queue is empty, so a new connection will
    // be created
    {
        connection = DBConnectionPool.createDBConnection();
    }

    return connection;
}

/**
 * Releases the connection represented by <code>pReleasedConnection</code>
 * parameter
 *
 * @param pReleasedConnection The db connection to release
 */
public static synchronized void releaseConnection(
        Connection pReleasedConnection) {

    // Add the connection to the free db connection queue
    DBConnectionPool.freeDbConnections.add(pReleasedConnection);
}

/**
 * Creates a new db connection
 *
 * @return A db connection
 * @throws SQLException
 */
private static Connection createDBConnection() throws SQLException {
    Connection newConnection = null;

    // Create a new db connection using the db properties
    // newConnection = DriverManager.getConnection(
    //    "jdbc:mysql://localhost/resources", "root", "");
    newConnection = DriverManager.getConnection(
            DBConnectionPool.dbProperties.getProperty("url"),
            DBConnectionPool.dbProperties.getProperty("username"),
            DBConnectionPool.dbProperties.getProperty("password"));

    newConnection.setAutoCommit(false);

    return newConnection;
}

private static void loadDbDriver() throws ClassNotFoundException {
    Class.forName(DBConnectionPool.dbProperties.getProperty("driver"));
}

/**
 * Loads the db properties
 *
 * @throws IOException
 */
private static void loadDbProperties() throws IOException {
    InputStream fileProperties = new FileInputStream("database.properties");
    DBConnectionPool.dbProperties = new Properties();

    DBConnectionPool.dbProperties.load(fileProperties);
}

}

注意:我的项目中有一个文件 Database.properties

  • driver=org.gjt.mm.mysql.Driver
  • url=jdbc:mysql://localhost/name_db
  • 用户名=root
  • 密码='密码'

我已经在其他项目中使用了 DBConnectionPool 类,并且它总是工作得很好。所以我不明白出了什么问题。也许与交易有关?

最佳答案

您在连接池中禁用自动提交(说真的:不要自己推出,使用现有的,他们会做得比这更好)。

您永远不会在代码中的任何地方调用 commit,因此结果永远不会提交(最终当连接真正关闭或以其他方式丢失时,更改将回滚)。

我的建议:

  1. 完成工作单元后调用 commit()(或 rollback())。
  2. 开始使用真正的连接池,例如 HikariCP、DBCP 或 c3p0

关于java - PreparedStatementexecute() 不影响数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38276650/

相关文章:

php - MySQL 三表连接——用户和好友图片

mysql - 如何在 MySQL 的 str_to_date 中使用 %U

php - PDO 插入不会添加到数据库

mysql - 如果您对表中的其他字段运行 UPDATE 语句,CURRENT_TIMESTAMP 字段会自动更新吗?

java - 如何对数据集的垂直数据库布局进行编程

mysql - 存储单个项目数据的表应该水平增长还是垂直增长?

java - 命名未定义数量的变量

java - 如果用户选择无效文件,则停止执行程序

java - 尝试修改游戏,以便程序保留未接受的答案列表并在最后打印它们。 (java)

java - 如何使用同步和异步方法正确 cooking DataStax 访问器?