简体   繁体   中英

get a database connection in java

This is my source code.

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());
        }
    }
}

Here i got an exception like "executeQuery method can not be used for update." What is this exception and how can I solve this. Thank you.

You need to use executeQuery like this

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM