How to connect to a database using JDBC? Assume that database name is testDb and it has table named employee which has 2 records.
SolutionFollowing example uses getConnection, createStatement & executeQuery methods to connect to a database & execute queries.
import java.sql.*; public class jdbcConn { public static void main(String[] args) { try { Class.forName("org.apache.derby.jdbc.ClientDriver"); } catch(ClassNotFoundException e) { System.out.println("Class not found "+ e); } System.out.println("JDBC Class found"); int no_of_rows = 0; try { Connection con = DriverManager.getConnection ( "jdbc:derby://localhost:1527/testDb","username", "password"); Statement stmt = con.createStatement(); ResultSet rs = stmt.executeQuery ("SELECT * FROM employee"); while (rs.next()) { no_of_rows++; } System.out.println("There are "+ no_of_rows + " record in the table"); } catch(SQLException e){ System.out.println("SQL exception occured" + e); } } }Result
The above code sample will produce the following result. The result may vary. You will get ClassNotfound exception if your JDBC driver is not installed properly.
JDBC Class found There are 2 record in the table
java_jdbc.htm
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4