

Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
Java SQL (JDBC) session. In this hands-on session, you will create a connection between Java and MySQL Server. Later, you will need to define several SQL ...
Typology: Summaries
1 / 2
This page cannot be seen from the preview
Don't miss anything!


PreparedStatement.
import java.sql.*; public class SQLdatabase { // JDBC driver name and database URL static final String JDBC_DRIVER = "com.mysql.jdbc.Driver"; static final String DB_URL = "jdbc:mysql://localhost/"; // Database credentials static final String USER = "root"; static final String PASS = "root"; // insert the password to SQL server public static void main(String[] args) { Connection conn = null ; Statement stmt = null ; try { // Register JDBC driver Class. forName ( JDBC_DRIVER ); // Open a connection System. out .println("Connecting to database..."); conn = DriverManager. getConnection ( DB_URL , USER , PASS ); / // Execute a query to create database System. out .println("Creating database...");
stmt = conn.createStatement(); String sql = "CREATE …"; // Create database students stmt.executeUpdate(sql); System. out .println("Database created successfully..."); // Connect to the created database STUDENTS and create table REGISTRATION conn = DriverManager. getConnection ( DB_URL + "STUDENTS", USER , PASS ); sql = "CREATE TABLE …”// Create table REGISTRATION with corresponding attributes stmt. ; System. out .println("Created table in given database successfully..."); // insert values into the table sql = "INSERT INTO Registration " + "VALUES (…)"; stmt. …; // repeat the procedure for all rows of the table System. out .println("Inserted records into the table..."); // create the java mysql update preparedstatement String query = "update registration …"; // Update age of Sumit Mittal PreparedStatement preparedStmt = conn.prepareStatement(query); … // execute p // insert a new values to the table with preparedstatement query = "insert into registration values(?, ?, ?, ?)"; // finish the statement . System. out .println("The table is updated..."); conn.close(); } catch (SQLException se){ //Handle errors for JDBC se.printStackTrace(); } catch (Exception e){ //Handle errors for Class.forName e.printStackTrace();} System. out .println("Goodbye!"); } }