Thursday, 7 June 2012

Variable Declarations

Connection newConnection=null;
PreparedStatement query;
ResultSet result;

 Code for Establish Database Connection

 Class.forName("com.mysql.jdbc.Driver").newInstance();
   newConnection=   (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/"+db,"root","");

//Should replace db with your database name

Code for insert data into database

 query= (PreparedStatement) newConnection.prepareStatement("insert into Table_Name(field1,field2,field3,field4) values(?,?,?,?) ");
query.setString(1,dataforfield1);
query.setLong(2,dataforfield2);
query.setLong(3,dataforfield3);
query.setLong(4,dataforfield4);
query.executeUpdate();

Code for Selection

         try{   query=(PreparedStatement) newConnection.prepareStatement("select * from TableName where Field1=?");

 query.setString(1,dataforfield1);
    result= query.executeQuery();

 //Result will be in variables "result".  " result.getString(1) " will return data in first column of current pointing row. 

result.next() will point next row in resultSet

Code for Deletion

 query=(PreparedStatement) newConnection.prepareStatement("delete from Tablename  where field1=?");
         query.setString(1, dataforfield1);
        query.executeUpdate();

Code for Updation

query =  (PreparedStatement) newConnection.prepareStatement("update Tablename set filed2=? where field1=?");
query.setString(1,data to be set in field2);
query.setStingt(2,pointing value for field1);
query.executeUpdate();

0 comments:

Post a Comment

Blogroll

Blogger templates

About