PreparedStatement java example mysql


PreparedStatement

  • PreparedStatementPreparedStatement is an interface which is in package of   jav.sql.PreparedStatemnet.
  • PreparedStatement interface object represents a precompiled SQL statements.
  • PreparedStatement is derived from the Statement class.
  • PreparedStatement interface can be created by calling prepareStatement() method.
  • The prepareStatement() method is available in java.sql.Connection interface.
  • The prepareStatement() method takes SQL statements in java programming format.
  • PreparedStatement interface   used to efficiently execute SQL statements more  then one time and input different value at Runtime means that  user can input different value multiple time through console input device like a keyboard.

Declaration of Object / variable required in PreparedStatement

String sql;
PreparedStatement ps;
ResultSet rs;
int er; (effected row number)

SELECT  QUERY

sql=”select * from mytable”;

ps=con.prepareStatement(sql);

rs=ps.executeQuery(sql);

INSERT QUERY

NO and NAME are Table Fields(columns)

no name are Java program variable no ,name value given by Keyboard

sql=”Insert into mytable(NO,NAME)values(?,?)”;

ps=con.prepareStatement(sql);

ps.setInt(1,no);

ps.setString(2,name);

er = ps.executeUpdate();

 

UPDATE  QUERY

sql=”update mytable set NAME = ? where NO=?”;

ps=con.prepareStatement(sql);

ps.setString(1,name);

ps.setInt(2,no);

er=ps.executeUpdate();

DELETE  QUERY

sql=”delete from mytable where no=?”;

ps=con.prepareStatement(sql);

ps.setInt(1,no);

er=ps.executeUpdate();

where each ? represent column index number in a table  here mytable have No and NAME two column so first ? refer NO and  second ? refer NAME column in table.

After this we set value to each ? by setter method by object of PreparedStatement interface different type of Different setter method.

 

PreparedStatement java example mysql

Project Name = project1
Class Name = Jdbc2

DartabseDriver =mysql

username =root

password =root

DataBase Name = mydatabase

Table Name = mytable

Table Column is No (int) and  Name (varchar)

Source Code in Java Eclipse

Output in Java Eclipse

Right click on Source code window
Run As – Java Application

 

 

see Example of CallableStatement in  java with mysql

(Visited 208 times, 1 visits today)

Leave a Reply

Your email address will not be published. Required fields are marked *


CAPTCHA Image
Reload Image