Java, XML, and database programming practices

Source: Internet
Author: User
When we started learning XML and database programming, we had no way to start with a lot of documents and materials. In my work, I just need to use this to sort out a program at hand. Its function is very simple. It uses java to import some data from the access database to the SQL database.
Requirements:
Original Access database table structure:
Table: production
Product Model string ......... Product NO.
Part Drawing Number string type .......... Part No.
Figure No. string type .......... Tool ID
SQL data table structure:
Project product table
Id int Id
Number... Varchar64 No.
Product parts table
Id int Id
Pid int product id (associated with the id in the project table)
Number... Varchar64 No.
Production tool table corresponding to Componenttype and parts
Id int Id
Aid int part id (associated with the id in the product table)
Number... Varchar64 No.
You must put the original numbers in the following SQL tables and associate them with IDs.
Considering that database connections may change, we decided to use xml to configure data connections. The content of the Dbs. xml file is as follows:
<? Xml version = "1.0" encoding = "GBK"?>
<Dbcopy>
<Source>
<Class> sun. jdbc. odbc. JdbcOdbcDriver </class>
<Url> jdbc: odbc: asrs </url>
<User> "" </user>
<Password> "" </password>
</Source>

<Dest>
<Class> com. microsoft. jdbc. sqlserver. SQLServerDriver </class>
<Url> jdbc: microsoft: sqlserver: // localhost: 1433; DatabaseName = vxms </url>
<User> vxms </user>
<Password> vxms </password>
</Dest>
</Dbcopy>

The ConnPara. java file represents the database connection parameters in the form of classes.
Public class ConnPara
{
String dbClass = null;
String url = null;
String username = null;
String password = null;

Public ConnPara (){}

Public ConnPara (String pdbClass, String purl, String pusername, String ppassword)
{
DbClass = pdbClass;
Url = purl;
Username = pusername;
Password = ppassword;
}

Public String getDbClass () {return dbClass ;}

Public String getUrl () {return url ;}

Public String getUsername () {return username ;}

Public String getPassword () {return password ;}

Public void setDbClass (String str) {dbClass = str ;}

Public void setUrl (String str) {url = str ;}

Public void setUsername (String str) {username = str ;}

Public void setPassword (String str) {password = str ;}

}
The DbXmlParser. java file encapsulates operations on xml files.

 

Import javax. xml. parsers .*;

Import org. w3c. dom .*;

Import org. xml. sax .*;

Import java. io .*;

 

Public class DbXmlParser

{

Static String xmlfile;

Public DbXmlParser (String filename)

{

Xmlfile = filename;

}

Public static Element loadDocument ()

{

Try

{

// Factory

DocumentBuilderFactory dcfactory = DocumentBuilderFactory. newInstance ();

// Document Constructor

Documentbuilder DB = dcfactory. newdocumentbuilder ();

// Constructed document

Document Doc = dB. parse (xmlfile );

// Root element

Element root = Doc. getdocumentelement ();

Return root;

} Catch (parserconfigurationexception e ){

System. Out. println ("parserconfigurationexception ");

E. printStackTrace ();

} Catch (IOException e ){

System. out. println ("IOException ");

E. printStackTrace ();

} Catch (SAXException e ){

System. out. println ("SAXException ");

E. printStackTrace ();

} Catch (Exception e ){

E. printStackTrace ();

}

Return null;

}

Public ConnPara getSource ()

{

Element root = loadDocument ();

If (root = null) {return null ;}

NodeList nodes = root. getElementsByTagName ("source ");

If (nodes. getLength ()> 0)

{

Node node = nodes. Item (0 );

String connclass = getchildelementvalue (node, "class ");

String url = getchildelementvalue (node, "url ");

String username = getchildelementvalue (node, "user ");

String Password = getchildelementvalue (node, "password ");

Return new connpara (connclass, URL, username, password );

}

Return null;

}

Public ConnPara getDest ()

{

Element root = loadDocument ();

If (root = null) return null;

NodeList nodes = root. getElementsByTagName ("dest ");

If (nodes. getLength ()> 0)

{

Node node = nodes. item (0 );

String connclass = getChildElementValue (node, "class ");

String url = getChildElementValue (node, "url ");

String username = getChildElementValue (node, "user ");

String password = getChildElementValue (node, "password ");

Return new ConnPara (connclass, url, username, password );

}

Return null;

}

// Obtain the value of the child element

Private String getChildElementValue (Node node, String subTagName)

{

String returnString = "";

If (node! = Null)

{

NodeList children = node. getChildNodes ();

For (int innerLoop = 0; innerLoop <children. getLength (); innerLoop ++)

{

Node child = children. item (innerLoop );

If (child = null | child. getNodeName () = null |! Child. getNodeName (). equals (subTagName ))

Continue;

Node grandChild = child. getFirstChild ();

If (grandChild. getNodeValue ()! = Null)

Return grandChild. getNodeValue ();

}

}

Return returnString;

}

}

The file DbInput. java is the real data copy part:

 

Import java. SQL .*;

 

Public class DbInput

{

Connection src = null;

Connection dest = null;

Connection connformax = null;

ConnPara srcPara;

ConnPara destPara;

Public DbInput (){}

Public void dbInit ()

{

DbXmlParser xmlparser = new DbXmlParser ("dbs. xml ");

SrcPara = xmlparser. getSource ();

DestPara = xmlparser. getDest ();

Try {

Class. forName ("sun. jdbc. odbc. JdbcOdbcDriver ");

Class. forName ("com. microsoft. jdbc. sqlserver. SQLServerDriver ");

Src = DriverManager. getConnection (srcPara. getUrl (), srcPara. getUsername (), srcPara. getPassword ());

Dest = DriverManager. getConnection (destPara. getUrl (), destPara. getUsername (), destPara. getPassword ());

Connformax = DriverManager. getConnection (destPara. getUrl (), destPara. getUsername (), destPara. getPassword ());

}

// Catch exceptions in the driver Loading

Catch (ClassNotFoundException cnfex ){

System. err. println ("failed to load the JDBC/ODBC driver. ");

Cnfex. printStackTrace ();

System. exit (1); // terminate program

} Catch (SQLException ex)

{

System. err. println ("connection failed ");

Ex. printStackTrace ();

System. exit (1); // terminate program

}

}

Public void copyproduct ()

{

Statement st = null;

ResultSet rset = null;

String sqlstr;

Try {

// Execute the SQL statement

String query = "select * from production ";

St = src. createStatement ();

Rset = st.exe cuteQuery (query );

Int pid, ljid, cid, ciid;

While (rset. next ())

{

String pnumber = rset. getString (1 );

String ljnumber = rset. getString (2 );

String cnumber = rset. getString (3 );

// Insert to the product table

Pid = getIdfromNumber ("project", "number", pnumber );

If (pid = 0) // Insert a new record

{

Pid = getMax ("project"); // System. out. println (pid );

Sqlstr = "Insert into project (id, number) values (" + pid + ", '" + pnumber + "')";

Execute (destPara, sqlstr );

}

// Insert to part table

Ljid = getIdfromNumber ("product", "number", ljnumber );

If (ljid = 0) // Insert a new record

{

Ljid = getMax ("product ");

Sqlstr = "Insert into product (id, pid, number) values (" + ljid + "," + pid + ", '" + ljnumber + "')";

Execute (destPara, sqlstr );

}

// Insert a tool table

Cid = getIdfromNumber ("componenttype", "number", cnumber );

If (cid = 0) // Insert a new record

{

Cid = getMax ("componenttype ");

Sqlstr = "Insert into componenttype (id, aid, number) values (" + cid + "," + ljid + ", '" + cnumber + "')";

Execute (destPara, sqlstr );

}

}

 

}

Catch (SQLException sqlex ){

Sqlex. printStackTrace ();

}

}

Protected boolean alreadyin (String tname, String colname, String value)

{

Int result;

ResultSet rst = null;

Try {

// Execute the SQL statement

String query = "select" + colname + "from" + tname + "where" + colname + "= '" + value + "'";

Statement statement = connformax. createStatement ();

Rst = statement.exe cuteQuery (query );

If (rst. next ())

{

Statement. close ();

Rst. close ();

Return true;

}

}

Catch (SQLException sqlex ){

Sqlex. printStackTrace ();

Return false;

}

Return false;

}

Protected int getidfromnumber (string tname, string colname, string value)

{

Int result;

Resultset rst = NULL;

Try {

Connection conn = drivermanager. getconnection (destpara. geturl (), destpara. GetUserName (), destpara. GetPassword ());

String query = "select ID," + colname + "from" + tname + "where" + colname + "= '" + value + "'";

System. Out. println (query );

Statement statement = conn. createstatement ();

RST = statement.exe cutequery (query );

If (RST. Next ())

{

Return RST. getint ("ID ");

}

}

Catch (SQLException sqlex ){

Sqlex. printStackTrace ();

Return 0;

}

Return 0;

}

/**

* Obtain the maximum ID of a table.

*/

Protected int getMax (String tname)

{

Int result;

ResultSet rst = null;

Try {

// Execute the SQL statement

String query = "select Max (id) from" + tname;

Statement statement = connformax. createStatement ();

Rst = statement.exe cuteQuery (query );

If (rst. next ())

{

Return rst. getInt (1) + 1;

}

}

Catch (sqlexception sqlex ){

Sqlex. printstacktrace ();

Return 0;

}

Return 1;

}

/**

* Execute an SQL statement

*/

Public static void execute (connpara, string stmt) throws sqlexception

{

Connection conn = null;

PreparedStatement ps = null;

Try {

Conn = DriverManager. getConnection (connpara. getUrl (), connpara. getUsername (), connpara. getPassword ());

System. out. println (stmt );

Ps = conn. prepareStatement (stmt );

Ps.exe cuteUpdate ();

} Catch (Exception e ){

E. printStackTrace ();

System. out. println (e. getMessage ());

} Finally {

If (ps! = Null) ps. close ();

If (conn! = Null) conn. close ();

}

}

Public static void main (String argc [])

{

DbInput copydb = new DbInput ();

Copydb. dbInit ();

Copydb. copyproduct ();

}

}

 

Problem:

1) The access database cannot be read and written directly by jdbc. The solution is to first configure access in ODBC and then operate the access database through ODBC.

2) com. microsoft. jdbc. sqlserver. SQLServerDriver class. This is because Microsoft's jdbc package needs to be downloaded when running this class. This package contains three files: msbase. jar, mssqlserver. jar, msutil. jar to include the three files.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.