【发布时间】:2014-10-18 15:36:48
【问题描述】:
我一直在尝试使用 Java 将值插入到我的数据库中。 这是我第一次尝试的代码。
Connection conn = null;
if(action.getSource() == btnAddItem)
{
String command =
"INSERT INTO item VALUES (" + itemNo + ", "
+ itemName + ", "
+ costprice + ", "
+ sellingprice + ", "
+ stock + ")";
try
{
this.executeInsert(conn, command); //works
//testPrint(command);
}
catch (SQLException e)
{
e.printStackTrace();
}
}
我使用 testPrint 方法单独检查以查看字符串命令中是否存在问题。但这种方法效果很好。 executeInsert 没有。这是我使用的executeInsert 方法:
public boolean executeInsert(Connection connection, String command) throws SQLException
{
try
{
Statement st = connection.createStatement();
st.executeUpdate(command);
connection.close();
}
catch (Exception e)
{
System.err.println("Got an exception!");
System.err.println(e.getMessage());
e.printStackTrace();
}
return false;
}
}
由于那不起作用,我浏览了一些教程并发现了有关 PreparedStatement 的信息。我尝试如下使用它(没有任何其他方法):
Connection conn = null;
if(action.getSource() == btnAddItem)
{
try
{
String command = "INSERT INTO item VALUES (?, ?, ?, ?, ?)";
PreparedStatement preparedStmt = (PreparedStatement) conn.prepareStatement(command);
preparedStmt.setString (1, itemNo);
preparedStmt.setString (2, itemName);
preparedStmt.setDouble (3, costprice);
preparedStmt.setDouble (4, sellingprice);
preparedStmt.setInt (5, stock);
preparedStmt.execute();
// conn.close();
}
catch (SQLException e)
{
e.printStackTrace();
}
}
现在,我有一个小小的预感,我的Connection conn = null 是问题所在。但我不知道还有什么设置它。
在这一点上,我已经诚实地尝试了所有我能做的事情,而且我对 Java 中的 SQL 连接部分仍然很陌生。所以你们可以提供的任何帮助或提示都会有很大的帮助。
谢谢。
编辑: 这是连接方法。
public Connection getConnection() throws SQLException
{
Connection conn = null;
Properties connectionProps = new Properties();
connectionProps.put("user", this.userName);
connectionProps.put("password", this.password);
conn = DriverManager.getConnection("jdbc:mysql://"
+ this.serverName + ":" + this.portNumber + "/" + this.dbName,
connectionProps);
return conn;
}
【问题讨论】:
标签: java sql connection