在DB2中创建表查询

时间:2016-01-23 15:43:25

标签: java db2

我想用Java代码创建DB2表。我测试了这段代码,但是我收到了错误:

  

com.ibm.db2.jcc.am.SqlException:[jcc] [10103] [10941] [4.19.26]方法   executeQuery不能用于更新。 ERRORCODE = -4476,SQLSTATE = null

public void testDB2TableWithRandomData() throws Exception
    {
        System.out.println("\nTesting SQL query for DB2 test table and data\n");
        try
        {
            Class.forName("com.ibm.db2.jcc.DB2Driver");
        }
        catch (ClassNotFoundException e)
        {
            System.out.println("Please include Classpath  Where your DB2 Driver is located");
            e.printStackTrace();
            return;
        }
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rset = null;
        try
        {
            conn = DriverManager.getConnection("jdbc:db2://34.137.10.143:20002/SAMPLE", "db2inst1", "pass");
            if (conn != null)
            {
                System.out.println("DB2 Database Connected");
            }
            else
            {
                System.out.println("DB2 connection Failed ");
            }
            pstmt = conn.prepareStatement("CREATE TABLE EMPL (ENO INTEGER, LASTNAME VARCHAR(30), HIREDATE DATE, SALARY INTEGER)");
            rset = pstmt.executeQuery();
            if (rset != null)
            {
                while (rset.next())
                {
                    System.out.println("Status: " + rset.getString(1));
                }
            }
        }
        catch (SQLException e)
        {
            System.out.println("DB2 Database connection Failed");
            e.printStackTrace();
            return;
        }
    }

从Java代码创建表的正确方法是什么?

1 个答案:

答案 0 :(得分:1)

您需要对INSERT,UPDATE,DELETE和DDL语句(如CREATE TABLE)使用pstmt.executeUpdate()