It
is a three step process.
Step
1: Load the driver
Ex:
Class.forName("com.mysql.jdbc.Driver");
Step
2: Get the Driver instance
Ex:
Driver driver =
DriverManager.getDriver("jdbc:mysql://localhost/world");
Step
3: Use the connect method of
Driver interface, to connect to database.
Ex:
Connection conn = driver.connect("jdbc:mysql://localhost/world",
props);
import java.sql.*; import java.util.*; public class SampleApp { public static void main(String args[]) throws SQLException, ClassNotFoundException{ Class.forName("com.mysql.jdbc.Driver"); Driver driver = DriverManager.getDriver("jdbc:mysql://localhost/world"); Properties props = new Properties(); String userName = "root"; String password = "tiger"; props.put("user", userName); props.put("password", password); Connection conn = driver.connect("jdbc:mysql://localhost/world", props); String query = "CREATE TABLE employee (id int, name varchar(30), PRIMARY KEY(id))"; Statement stmt = conn.createStatement(); stmt.execute(query); /* Insert data to employee table */ query = "INSERT INTO employee values(1, \"Krishna\")"; stmt.execute(query); query = "INSERT INTO employee values(2, \"Arjun\")"; stmt.execute(query); query = "INSERT INTO employee values(3, \"Joel\")"; stmt.execute(query); System.out.println("Calling roll back operation"); query = "SELECT * FROM employee"; ResultSet rs = stmt.executeQuery(query); while(rs.next()){ int id = rs.getInt("id"); String name = rs.getString("name"); System.out.println(id +" " + name); } System.out.println("Dropping table employee"); query = "DROP TABLE employee"; stmt.execute(query); rs.close(); stmt.close(); conn.close(); } }
Output
Calling roll back operation 1 Krishna 2 Arjun 3 Joel Dropping table employee
No comments:
Post a Comment