使用jdbc可编程地将数据插入mysql数据库时出现问题。问题如下:
当我在数据库中插入新用户时,我得到一个新连接,创建一个准备好的语句并执行查询。所有方法都有,但数据库中没有显示任何结果。
让我们举个例子。
让我们假设我使用MySql查询浏览器在数据库中手动添加新用户。
然后假设我决定以可编程方式添加新用户:
最后我手动添加了一个新用户: name = pluto,pin = 3434。
现在我的表格结果为:
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我已经在其他项目中使用过DBConnectionPool类,它总能正常工作。所以我不明白什么是错的。也许有关交易的事情?
答案 0 :(得分:1)
您在连接池中禁用自动提交(严重:不要自己动手,使用现有的,他们会比这更好)。
你永远不会在代码中的任何地方调用commit,因此结果永远不会被提交(并且最终当连接真正关闭或以其他方式丢失时,更改将被回滚)。
我的建议:
commit()
(或rollback()
)。答案 1 :(得分:0)
您需要使用executeUpdate()而不是execute()。
https://docs.oracle.com/javase/7/docs/api/java/sql/Statement.html#executeUpdate(java.lang.String)
int executeUpdate(String sql) 抛出SQLException
执行给定的SQL语句,可以是INSERT,UPDATE或 DELETE语句或不返回任何内容的SQL语句,例如 SQL DDL语句。
https://docs.oracle.com/javase/7/docs/api/java/sql/Statement.html#execute(java.lang.String)
布尔执行(String sql) 抛出SQLException
execute方法执行SQL语句并指示其形式 第一个结果。然后,您必须使用方法getResultSet或 getUpdateCount用于检索结果,getMoreResults用于移动 任何后续结果。