【发布时间】:2015-05-25 19:06:24
【问题描述】:
我正在使用 MySQL 服务器 5.6、Tomcat 8.0。我可以创建一个 SQL 输入语句,它成功地将硬编码值放入我的表中,但如果我尝试使用变量,它在表中显示为 NULL。我在 SQL 语句之前有 println 语句,它们在变量中显示了正确的值。我的语法看起来正确,正如我所说,它适用于硬编码值。 请原谅代码格式。这应该是一个快速(HA!)且肮脏的概念证明。
代码sn-p:
// method to update spice table with input data
public void update()
{
System.out.println("Starting Update");
java.sql.Date useDate = new java.sql.Date(convert(date));
Connection conn = null;
Statement stmt = null;
String sql;
try{
System.out.println("Starting try...");
// Register JDBC driver
Class.forName("com.mysql.jdbc.Driver");
// Open a connection
System.out.println("Connecting to database...");
conn = DriverManager.getConnection(DB_URL,USER,PASS);
System.out.println("Connected database successfully...");
// Execute update
System.out.println("Creating statement...");
stmt = conn.createStatement();
System.out.println("Name is " + name +".");
System.out.println("Name is " + getName() +".");
sql = "INSERT INTO spices VALUES (name, 'location', 'container', 'status', useDate)";
stmt.executeUpdate(sql);
// Clean-up environment
stmt.close();
conn.close();
}catch(SQLException se){
//Handle errors for JDBC
System.out.println("errors for JDBC");
se.printStackTrace();
}catch(Exception e){
//Handle errors for Class.forName
System.out.println("errors for Class.forName");
e.printStackTrace();
}finally{
//finally block used to close resources
try{
if(stmt!=null)
stmt.close();
}catch(SQLException se2){
System.out.println("SQLException - stmt.close()");
}// nothing we can do
try{
if(conn!=null)
conn.close();
}catch(SQLException se){
System.out.println("SQLException - conn.close()");
se.printStackTrace();
}//end finally try
}//end try
System.out.println("Goodbye!");
}
显示 println 输出的服务器日志:
2015-05-25 19:37:46 Commons Daemon procrun stdout initialized
Starting Update
Starting try...
Connecting to database...
Connected database successfully...
Creating statement...
Name is chilli.
Name is chilli.
Goodbye!
表格输出:
| NULL | location | container | status | NULL |
第一个 NULL 应该说“辣椒”。 任何帮助将不胜感激 - 我在这里扯头发! 千瓦
【问题讨论】:
-
不应该是:sql = "INSERT ....'" + name + "'....'" + useDate + "')" 你的变量在字符串之外跨度>
-
分享你打印“2015-05-25 19:37:46 Commons Daemon procrun stdout initialized”行的代码。
-
Arin,Tomcat 在启动日志时会这样写。