Hello Friends,
This is the simple example for executing the SQL statements to INSERT, UPDATE or DELETE any records from the database using JDBC. In the below code I have explained all the three operations. When we insert, update or delete any records from the database we are updating the database, hence we use the executeUpdate() function with the Statement.
Please take the note that whenever you provide the String/Text values for update then add the values in between ” ” or ‘ ‘. This is mandatory for all the Sting types else the DB will not recognize the values and will throw the error. Following is the code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 |
package com.JavaExamples; import java.sql.*; public class JDBCConnectionExample { public static void main(String[] args) { System.out.println("MySQL & JDBC Connect Example."); Connection conn = null; String url = "jdbc:mysql://localhost:3306/"; String dbName = "code2java";// Database name String driver = "com.mysql.jdbc.Driver"; String userName = "username"; String password = "password"; String dbtime = null; try { Class.forName(driver).newInstance(); conn = DriverManager.getConnection(url+dbName,userName,password); System.out.println("Database Connected"); Statement stmt = conn.createStatement(); //For inserting the data into database String insertQuery = "INSERT table_name(column_1,column_2,column_3,...) values(value_1,value_2,value_3,...)"; stmt.executeUpdate(insertQuery); //For Updating the particular entity of the table String updateQuery = "UPDATE table_name SET column_name1=value_1,column_name2=value_2 WHERE column_name=some_value"; stmt.executeUpdate(updateQuery); //For Deleting the specific row/s in the table String deleteQuery = "DELETE FROM table_name WHERE column_name=some_value"; stmt.executeUpdate(deleteQuery); } catch(Exception e) { e.printStackTrace(); } finally { //This is used for Disconnecting.. try { conn.close(); System.out.println("Database Disconnected"); } catch (SQLException e) { e.printStackTrace(); System.out.println("Error while Disconnecting from database"); } } } } |
Hope this will help you.
Regards,
Nikhil Naoghare.
You actually make it seem so easy along with your presentation however I to find this topic to be actually one thing which I think I might by no means understand. It kind of feels too complex and very extensive for me. I am looking forward in your subsequent put up, I’ll try to get the cling of it!
Good job!!Well done!