从Java连接到DB2

时间:2014-07-08 17:06:10

标签: java database jdbc db2

我正在尝试将Java程序连接到IBM的DB2数据库,这是代码

Class.forName("com.ibm.db2.jcc.DB2Driver").newInstance();
Connection db2Conn = DriverManager.getConnection("jdbc:db2://localhost:50000/N","R","k");
Statement st=db2Conn.createStatement();
st.executeUpdate("INSERT INTO NTTP VALUES('MANOJ SAINI','iskcon110','Rajasthan','Male','july 2 2014','C')");

我在Statement st = db2Conn.createStatement();

处收到语法错误
Type mismatch: cannot convert from java.sql.Statement to java.beans.Statement 

以及st.executeUpdate()处的更多内容,作为此行的多个标记

    - The method executeUpdate(String) is undefined for the type Statement
    - Syntax error, insert ";" to complete Statement
    - Syntax error, insert "AssignmentOperator Expression" to complete 
     Assignment
    - MANOJ cannot be resolved to a variable
    - Syntax error, insert ";" to complete Statement
    - Syntax error, insert ")" to complete MethodInvocation.

我是DB2的新手,无法弄清楚出了什么问题。

2 个答案:

答案 0 :(得分:1)

您的SQL语法可能在SQL REPL中起作用,但在Java中,那些不是有效的字符串 - 您也需要转义\,因为它是Java中的特殊字符,< / p>

java.sql.Statement st=db2Conn.createStatement();
st.executeUpdate(
       "INSERT INTO NTTP VALUES('MANOJ SAINI','iskcon110',"
     + "'Rajasthan','Male','july 2,2014',"
     + "'C:\\Users\\Ramveer\\Documents\\res')");

此外,您应该考虑使用PreparedStatement并绑定参数。

答案 1 :(得分:0)

首先,错误建议您尝试从java.beans.Statement而不是java.sql.Statement导入Statement,然后尝试使用java.sql.PreparedStatement代替java.sql.Statement

这样的事情:

String sql = "INSERT INTO student(student_id,student_name,class) VALUES(?,?,?)";
PreparedStatement statement = conn.prepareStatement(sql); 
statement.setInt(1, 7);
statement.setString(2,"MANOJ SAINI");
statement.setString(3,"Rajasthan");