在java中获取数据库连接

时间:2015-02-25 06:05:42

标签: java mysql sql-server

这是我的源代码。

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.ResultSet;

public class DBConnect {

    public static void main(String[] args) {

        try {
            String host = "jdbc:derby://localhost:1527/Employee";
            String uName = "jayani";
            String uPass = "jayani";
            Connection con = DriverManager.getConnection(host, uName, uPass);
            Statement stmt = con.createStatement();
            String sql = "SELECT*FROM WORKERS";

            ResultSet rs = stmt.executeQuery(sql);

            while (rs.next()) {
                int id_col = rs.getInt("ID");
                String fname = rs.getString("FIRST_NAME");
                String lname = rs.getString("LAST_NAME");
                String job = rs.getString("JOB_TITLE");

                System.out.println(id_col + "" + fname + "" + lname + "" + job);

            }
        } catch (SQLException ex) {

            System.out.println(ex.getMessage());
        }
    }
}

这里我得到一个例外" executeQuery方法不能用于更新。" 什么是这个例外,我该如何解决这个问题。 谢谢。

1 个答案:

答案 0 :(得分:1)

您需要像这样使用executeQuery

    Statement stmt = null;
    String query = "select * from <tablename>";
    stmt = con.createStatement();
    ResultSet rs = stmt.executeQuery(query);