2013-04-29 98 views
0

我想插入到我的MYSQL數據庫,但我的代碼總是去catch部分(這表示上傳到數據庫失敗)。我究竟做錯了什麼?插入MySQL查詢

public static Connection getAttConnection() throws Exception { 
    String url = "jdbc:mysql://localhost:3306/"; 
    String dbName = "VB"; 
    String driver = "com.mysql.jdbc.Driver"; 
    String userName = "root"; 
    String password = "***********"; 
    Class.forName(driver); 
    Connection conn = DriverManager.getConnection(url+dbName,userName,password); 
    return conn; 
} 

public static void addAttendance(String name, String type, String size, 
    String path, String last_Mod) { 
    Connection conn = null; 
    PreparedStatement pstmt = null; 
    boolean committed = false; 
    try { 
     conn = getAttConnection(); 
     conn.setAutoCommit(false); 
     String query = "INSERT INTO upload (name, type, size, path, last_Mod) VALUES (?,?,?,?,?)"; 
     pstmt = conn.prepareStatement(query); 
     pstmt.setString(1,name); 
     pstmt.setString(2,type); 
     pstmt.setString(3,size); 
     pstmt.setString(4,path); 
     pstmt.setString(5,last_Mod); 
     pstmt.executeUpdate(); 
     conn.commit(); 
     conn.setAutoCommit(true); 
     committed = true; 
     System.out.println("Upload Correctly"); 
    } catch (Exception e) { 
     System.err.println("Uploading to database failed"); 
    } 
} 
+0

您可以打印堆棧跟蹤而不是顯示自定義消息嗎? – 2013-04-29 13:59:39

+0

嘗試在catch中打印StackTrace以查看錯誤 – 2013-04-29 13:59:47

+0

是,給我一秒 – user2264202 2013-04-29 13:59:53

回答

0

您的密碼是否正確提供?您的代碼顯示其全部「*

接下來,檢查數據庫名稱。

然後,而不是打印自定義消息,打印整個例外,像這樣:

e.printStackTrace(System.out); 
0

不能完全確定,但你可能將字符串不帶引號....

String query = "INSERT INTO upload (name, type, size, path, 
       last_Mod) VALUES ('?','?','?','?','?')"; 

您將所有參數作爲字符串傳遞,但我懷疑大小應該是int。

0

我懷疑數據類型可能有問題,例如,當你做

pstmt.setString(3, size); 

你確定size是你的數據庫表中的字符串嗎?

另外,請加

e.printStackTrace(); 

catch()子句,以獲得更詳細的錯誤消息。

+0

他正在談論數據庫表中的TYPE,而不是Java類型! – NINCOMPOOP 2013-04-29 14:03:51