Monday 30 May 2011

Storing xml data into the database


I have to store this file into database

<?xml version="1.0" encoding="ISO-8859-1"?>
<?xml-stylesheet type="text/xsl" href="cdcatalog.xsl"?>
<entertainment category="video">
<movie genre="hollywood">
<title>Ironman2</title>

<artist >
<male>Robert Downing Junior</male>
<female>gwyneth paltrow</female>
</artist>

<country>USA</country>
<company>Columbia pictures</company>
<cost>1000 million</cost>
<release>2010 7 may</release>
</movie>
<movie genre="bollywood">
<title>Kites</title>
<artist >
<male>Hrithik Roshan</male>
<female>barbara mori</female>
</artist>
<country>India</country>
<company>FilmKraft India</company>
<cost>500 million</cost>
<release>2010 17 may</release>
</movie>


</entertainment>

import javax.xml.parsers.*;
import javax.xml.parsers.*;
import org.w3c.dom.*;
import java.sql.*;

public class xml{
public static void main(String[] args) {
try{
Class.forName("com.mysql.jdbc.Driver");
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/register";, "root", "root");
Statement st=connection.createStatement();
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse("movie.xml");
NodeList n1= doc.getElementsByTagName("title");
NodeList n2= doc.getElementsByTagName("male");
NodeList n3= doc.getElementsByTagName("female");
NodeList n4= doc.getElementsByTagName("country");
NodeList n5= doc.getElementsByTagName("company");
NodeList n6= doc.getElementsByTagName("cost");
NodeList n7= doc.getElementsByTagName("release");
for(int i=0;i<n1.getLength();i++){
String st1= n1.item(i).getFirstChild().getNodeValue();
String st2= n2.item(i).getFirstChild().getNodeValue();
String st3= n3.item(i).getFirstChild().getNodeValue();
String st4= n4.item(i).getFirstChild().getNodeValue();
String st5= n5.item(i).getFirstChild().getNodeValue();
String st6= n6.item(i).getFirstChild().getNodeValue();
String st7= n7.item(i).getFirstChild().getNodeValue();
System.out.println(st1+" "+st2+" "+st3+" "+st4+" "+st5+" "+st6+" "+st7);
st.executeUpdate("insert into movie(title,male,female,country,company,cost,movierelease) values('"+st1+"','"+st2+"','"+st3+"','"+st4+"','"+st5+"','"+st6+"','"+st7+"')");
}
}
catch(Exception e){
e.printStackTrace();
}
}
}

For the above code, we have created following database table:

CREATE TABLE `movie` (
`id` bigint(255) NOT NULL auto_increment,
`title` varchar(255) default NULL,
`male` varchar(255) default NULL,
`female` varchar(255) default NULL,
`country` varchar(255) default NULL,
`company` varchar(255) default NULL,
`cost` varchar(255) default NULL,
`movierelease` varchar(255) default NULL,
PRIMARY KEY (`id`)
)

No comments:

Post a Comment