Engineering Full Stack Apps with Java and JavaScript
1. Downloading, installing and configuring the database
See the installation and configuration note for your database.
2. Create table and insert data as:
Create table employee(empName varchar(20), id int PRIMARY KEY)
insert into employee values (‘name1’,1)
insert into employee values (‘name2’,2)
This example has been tested with Oracle XE and should most probably work with other database as well. See the installation and configuration note for your database.
3. Installing required jar files
Download and install the required jar files for your database. Please refer to javajee.com/jdbc-drivers-and-connection-strings and see if your database is listed there. Else use a google search and find out.
4. Find out the connection string for your particular database driver. Please refer to javajee.com/jdbc-drivers-and-connection-strings and see if your database is listed there.
Below example uses the connection url for Oracle XE and hence if you are using Oracle XE you don't have to make any changes:
String url = "jdbc:oracle:thin:@localhost:1521:XE";
Please replace it with the one for your database.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class MyFirstJDBCProgram {
public static void main(String args[]) {
try {
String url = "jdbc:oracle:thin:@localhost:1521:XE";
String username = "javaapp";
String password = "javaapp";
Connection con = DriverManager.getConnection(url, username, password);
System.out.println("connected");
Statement st = con.createStatement();
ResultSet rs = st.executeQuery("select * from employee");
while (rs.next()) {
System.out.println(rs.getString("empname"));
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
Now execute the program and see the result.
Note: You might have to modify the url based on your installation.
Comments
Error
"Error: Could not find or load main class MyFirstJDBCProgram" this message has been shown in the console. what is the wrong here ?
Please try running using
Please try running using command line and see.