Last active
August 29, 2015 14:04
-
-
Save kenorb/62a8e206f272d0dc3d45 to your computer and use it in GitHub Desktop.
JDBC API Demo 2
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* JDBC API Demo 2 | |
* | |
* PreparedStatement is pre-compiled statement and activites include: | |
* - load the query | |
* - parse the query | |
* - execute the query | |
* - save the query | |
* | |
* Usage: | |
* - Download the connector from http://dev.mysql.com/downloads/connector/j/ | |
* - Configure your classpath system variable to point to your connector .jar file. | |
* - Run your MySQL server. | |
* - Go to phpmyadmin and create training table with 4 columns: id, name, course, address | |
* - Run: | |
* - javap com.mysql.jdbc.Driver | |
* - javac Jdbc2.java | |
* - java Jdbc2 | |
*/ | |
import java.sql.*; | |
import java.io.*; | |
class Jdbc2 { | |
public static void main(String[] args) throws Exception { | |
// Load the driver. | |
Class.forName("com.mysql.jdbc.Driver"); | |
// Establish the connection to the existing database: training. | |
Connection con = DriverManager.getConnection("jdbc:mysql://localhost/training", "root", ""); | |
System.out.println("Connected!"); | |
// Create a statement. | |
PreparedStatement pst = con.prepareStatement("INSERT INTO student (name, course, address) VALUES (?, ?, ?)"); | |
// Execute the query | |
BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); | |
System.out.println("Enter name"); | |
String name = br.readLine(); | |
System.out.println("Enter course"); | |
String course = br.readLine(); | |
System.out.println("Enter address"); | |
String address = br.readLine(); | |
// Replace ?s | |
pst.setString(1, name); | |
pst.setString(2, course); | |
pst.setString(3, address); | |
// Notes: | |
// execute() is for all commands. | |
// executeQuery() is for SELECT only. | |
// executeUpdate() is for INSERT, UPDATE & DELETE. | |
int i = pst.executeUpdate(); | |
if (i > 0) { | |
System.out.println(i + " record created."); | |
} else { | |
System.out.println("Query failure!"); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment