2013-12-09 45 views
0

我想在dabase插入與下面的代碼錯誤在JDBC

try{ 
String driver = "sun.jdbc.odbc.JdbcOdbcDriver"; 
String url = "jdbc:odbc:ProductDSN"; 
Class.forName(driver); 
Connection con = DriverManager.getConnection(url); 
System.out.println("Connection established"); 
System.out.println("clear point 1"); 
String sql = "INSERT INTO product 
(id,productName,category,price,availability,quantity,description) 
VALUES('ID','name','catag','price','avail','quantity','discript')"; 
System.out.println("clear point 2"); 
PreparedStatement stmt = con.prepareStatement(sql); 
System.out.println("clear point 3"); 
stmt.executeUpdate(); 
System.out.println("clear point 4"); 

JOptionPane.showMessageDialog(null, "Record Save Successfully"); 

if (con != null) 
    stmt.close(); 
con.close(); 
System.out.println("Connection Closed"); 
} 
catch(SQLException sqle) 
{ 
    System.err.println("Error is in save method"); 
    System.err.println(sqle); 
} 

及以下插入statment是編譯錯誤..

Connection established 
clear poitn 1 
clear point 2 
clear point 3 
Error is in save method 
java.sql.SQLException: General error 
+2

表的所有數據類型都只是varchar? – Ashok

+2

請提供堆棧跟蹤 – 2013-12-09 06:08:26

+2

請檢查'id','price'和'quantity'的數據類型,無論它們是整數還是varchar – rachana

回答

0

SQL異常意味着誤差爲int SQL查詢。 在查詢瀏覽器上單獨檢查您的sql查詢。 檢查您是否已經給所有屬性的數據類型爲字符串.. 你給插入值作爲Strings..price,ID等。

檢查它是否在DB也相同的字符串格式.. PLZ提供錯誤顯示,所以我可以幫助您更多..

2

您對Prepared語句感到困惑。

的設置方法(setShort,setString等等上)用於設置IN 參數值必須指定與該 定義SQL類型的輸入參數的兼容的類型。例如,如果IN 參數的SQL類型爲INTEGER,則應使用setInt方法。

所以請儘量

String sql = "INSERT INTO product 
(id,productName,category,price,availability,quantity,description) 
VALUES(?,?,?,?,?,?,?)"; 

stmt.setInt(1, value)// for Integer where 1 is the index 
stmt.setString(2, value)// for string where 2 is the index 
..... 

最後,

stmt.executeUpdate(); 
0

退房準備好的語句格式&如何使用它。

+0

ling.s提供了很好的解釋。 – Aditya