高手帮忙改一下程序,读取XML文件连接数据库 谢谢
beanJava code
package bean;
public class db {
private String driver;
private String url;
private String uname;
private String upwd;
public String getDriver() {
return driver;
}
public void setDriver(String driver) {
this.driver = driver;
}
public String getUname() {
return uname;
}
public void setUname(String uname) {
this.uname = uname;
}
public String getUpwd() {
return upwd;
}
public void setUpwd(String upwd) {
this.upwd = upwd;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
}
xml文件
<?xml version="1.0" encoding="UTF-8"?>
<数据库连接>
<连接 id ="1">
<driver>sun.jdbc.odbc.JdbcOdbcDriver </driver>
<url>jdbc:odbc:aaa </url>
<uname>"" </uname>
<upwd>"" </upwd>
</连接>
</数据库连接>
类
Java code
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import bean.db;
public class TestX {
public static void main(String args[]){
db b = new db();
String driver = b.getDriver();
String url=b.getUrl();
String uname=b.getUname();
String upwd=b.getUpwd();
Connection con = null;
ResultSet rs = null;
Statement st = null;
try {
Class.forName(driver);
con=DriverManager.getConnection(url, uname, upwd);
st = con.createStatement();
rs = st.executeQuery("select * from student");
while(rs.next()){
System.out.println(rs.getString("sid"));
}
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void get() throws Exception{
String driver ;
String url;
String uname;
String upwd;
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse("src\\a.xml");
NodeList nl = doc.getElementsByTagName("连接");
for (int i = 0; i < nl.getLength(); i++) {
Element n = (Element) nl.item(i);
System.out.println(n.getAttribute("id"));
NodeList l = n.getElementsByTagName("driver");
driver=l.item(0).getFirstChild().getNodeValue();
NodeList l1 = n.getElementsByTagName("url");
url=l1.item(0).getFirstChild().getNodeValue();
NodeList l2 = n.getElementsByTagName("uname");
uname=l2.item(0).getFirstChild().getNodeValue();
NodeList l3 = n.getElementsByTagName("upwd");
upwd=url=l3.item(0).getFirstChild().getNodeValue();
db s = new db();
s.setDriver(driver);
s.setUrl(url);
s.setUname(uname);
s.setUpwd(upwd);
}
}
}
错误信息 Exception in thread "main" java.lang.NullPointerException
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Unknown Source)
at TestX.main(TestX.java:25)