You
can load the JDBC drivers by creating an object using the vendor's
JDBC Driver class.
/* Step 1: Import sql package */ import java.sql.*; import com.mysql.jdbc.Driver; public class SampleApp { public static void main(String args[]) throws SQLException, ClassNotFoundException{ /* Step 2: Load Driver */ System.out.println("Loading/Registering driver"); Driver driver = new Driver(); /* Step 3: Open connection to database */ System.out.println("Connecting to database"); String url = "jdbc:mysql://localhost/sample"; String userName = "root"; String pasword = "tiger"; Connection conn = DriverManager.getConnection(url, userName, pasword); /* Create table employee */ 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 = "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
Loading/Registering driver Connecting to database 1 Krishna 2 Arjun Dropping table employee
No comments:
Post a Comment