如以下代码:
/*
这是C#写的一个DATABASE连接类...
*/
using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;//引用这个命名空间
namespace Conn
{
public class DataBase
{
SqlConnection myConn;
public DataBase()
{
myConn = new SqlConnection();
try
{
//将SQL连接字符串指向CONFIG文件中的KEY,其对应的VALUE值写上连接字符串.
// CONFIG文件在下面贴出...
myConn.ConnectionString = ConfigurationManager.AppSettings["sqlString"];
}
catch (Exception ex)
{
string errors = ex.Message;
}
}
public SqlConnection GetConn()
{
return myConn;
}
}
}
这是App.Config文件.在这里可以让用户自行修改数据库的地址,帐号,密码,库名...
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<!--database中连接字符串,包括服务器地址,数据库帐号密码,数据库名 -->
<add key="sqlString" value="server=(local);uid = sa;pwd = sa;database = dataName"/>
</appSettings>
</configuration>
下面是JAVA写的一个DataBase类...
如何在JAVA中也像.NET一样来配置一个可以让用户自行修改数据库相关参数的XML文件呢?
在JAVA中用JTDS驱动连接SQL SERVER 2000数据库.
package artical.Conn;
import java.sql.*;
public class DataBase {
//应该修改这几个定义的几个变量了,如何去写一个XML文件,并且在JAVA中找到相关的类去调用写好的XML,并且将指定的参数的字符串指向XML中指定的KEY.
private String DatabaseName = "ArticalDB"; //数据库名称
private String DataUser = "sa"; //数据库帐号
private String DataPass = "sa"; //数据库密码
private String DBdriver = "net.sourceforge.jtds.jdbc.Driver"; //JTDS连接驱动
private String DBurl = "jdbc:jtds:sqlserver://localhost:1433/" +DatabaseName; //数据库连接路径加上数据库名
private Connection Conn = null;
public DataBase() {
try {
Class.forName(DBdriver);
} catch (ClassNotFoundException ex) {
ex.printStackTrace();
}
try {
Conn = DriverManager.getConnection(DBurl,DataUser,DataPass);
} catch (SQLException ex1) {
ex1.printStackTrace();
}
}
public Connection getConn() {
return Conn;
}
}
正如我在代码注释中所说的.如何去找个类来调用相关的XML文件中的KEY呢.
也就是在DB类,变量指向一个KEY,这个KEY的VALUE正是现在在代码中的变量所赋的值.
或者说,如何在JAVA中做成跟.NET样,通过XML文件来获取数据库连接参数.
哪位前辈可否为我提供些示例代码?
8 个解决方案
#1
我顶起来...拜托哪位前辈为我解决一下...
#2
感觉应该差不多吧...你也应该在事先在XML文档中写好连接数据库所使用的参数..
然后在应用程序中通过DOM/JDOM/SAX等读取XML文档中的数据来连接数据库
然后在应用程序中通过DOM/JDOM/SAX等读取XML文档中的数据来连接数据库
#3
想法是好的,在SPRING框架中可以很好的实现
#4
好了.我解决了~~
真TNND是个麻烦的问题...
从网上找了一堆不完整的代码,东拼西凑.总算完成了我的想法...
稍后我把总结出来的经验和源代码贴上来...
这可真TNND是个麻烦东西....
真TNND是个麻烦的问题...
从网上找了一堆不完整的代码,东拼西凑.总算完成了我的想法...
稍后我把总结出来的经验和源代码贴上来...
这可真TNND是个麻烦东西....
#5
将数据库链接的那些参数写入固定格式的XML文件,然后运行程序时候读XML,后台拼接字符串
我做过一个类似的,至少是可行的
我做过一个类似的,至少是可行的
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
import javax.xml.parsers.*;
import javax.xml.transform.*;
import org.w3c.dom.*;
import org.xml.sax.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
public class CreateXMLForEnterServelet extends HttpServlet {
private static final String CONTENT_TYPE = "text/html; charset=GBK";
//Initialize global variables
public void init() throws ServletException {
}
//Process the HTTP Get request
public void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
response.setContentType(CONTENT_TYPE);
PrintWriter out = response.getWriter();
//获取传递过来的值
String databaseType = request.getParameter("select");
String userName = request.getParameter("userName");
String userPassword = request.getParameter("userPassword");
String dbName = request.getParameter("dbName");
String dbSouse = request.getParameter("dbSouces");
int port = Integer.parseInt(request.getParameter("portNum"));
Document doc;
Element root;
try
{
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
String path = request.getRealPath("/");
File file = new File( path + "/" + "DBInfo.xml");
if(!file.exists())
{
doc = db.newDocument();
root = doc.createElement("DBInfo");
doc.appendChild(root);
}
else
{
doc = db.parse(file);
root = doc.getDocumentElement();
}
//添加子节点
Element rowNode = doc.createElement(databaseType);
root.appendChild(rowNode);
Node node = doc.createElement("Driver");
Node nodestr = doc.createElement("ConnectString");
Node serverName = doc.createElement("ServerName");
Node nodeName = doc.createElement("UserName");
Node nodePWD = doc.createElement("PassWord");
Node nodePort = doc.createElement("Port");
Node nodeDB = doc.createElement("DataBase");
rowNode.appendChild(node);
rowNode.appendChild(nodestr);
rowNode.appendChild(serverName);
rowNode.appendChild(nodeDB);
rowNode.appendChild(nodeName);
rowNode.appendChild(nodePWD);
rowNode.appendChild(nodePort);
String nodeValue;//Driver
String nodeConStr;//连接字符串
if(databaseType.equals("ORACLE"))
{
nodeValue = "oracle.jdbc.driver.OracleDriver";
nodeConStr = "jdbc:oracle:thin";
}
else
{
nodeValue = "com.microsoft.jdbc.sqlserver.SQLServerDriver";
nodeConStr = "jdbc:microsoft:sqlserver";
}
Text text = doc.createTextNode(nodeValue);
Text textstr = doc.createTextNode(nodeConStr);
Text textName = doc.createTextNode(userName);
Text textPWD = doc.createTextNode(userPassword);
Text textServer = doc.createTextNode(dbName);
Text textPort = doc.createTextNode(String.valueOf(port));
Text textDB = doc.createTextNode(dbSouse);
node.appendChild(text);
nodestr.appendChild(textstr);
nodeName.appendChild(textName);
nodePWD.appendChild(textPWD);
serverName.appendChild(textServer);
nodePort.appendChild(textPort);
nodeDB.appendChild(textDB);
DOMSource doms = new DOMSource(doc);
StreamResult sr = null;
TransformerFactory tff = TransformerFactory.newInstance();
Transformer tf = tff.newTransformer();
sr = new StreamResult(file);
tf.transform(doms,sr);
out.println("<h1>Create XMLFile Is Ok!!</h1>");
request.getRequestDispatcher("index.jsp").forward(request,response);
}
catch(Exception ex)
{
out.println("<h1>生成 XML 配置文件时出现错误:</h1><br/><h4>"+ex+"</h4>");
out.println("<br/><br/>");
out.print("<a href='index.jsp'>【点这里回到首页】</a>");
}
out.close();
}
//Process the HTTP Post request
public void doPost(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
doGet(request, response);
}
//Clean up resources
public void destroy() {
}
}
#6
楼上的,强!
不过你这样写也还是只限于Oracle 和 MSSQL , 其实你更应该读个已经存在的XML,自己写个DTD文件来固定格式,这样才是真正意义的扩展,可以添加任意类型的DB。不过现在Spring已经解决了
不过你这样写也还是只限于Oracle 和 MSSQL , 其实你更应该读个已经存在的XML,自己写个DTD文件来固定格式,这样才是真正意义的扩展,可以添加任意类型的DB。不过现在Spring已经解决了
#7
我解决了...我用JBULIDER 2006写的...
我的代码如下:
mysqlConfig.xml
ConfigParser.java
ParseXML.java
ReadConfigXml.java
DataBase.java
我的代码如下:
mysqlConfig.xml
[BanUBB]
<?xml version="1.0" encoding="UTF-8"?>
<!--
自行修改下列参数!
servername --> 服务器名称或地址
serverport --> 服务器端口
databasename --> 数据库名
username --> 数据库帐号
password --> 数据库密码
-->
<reportenv>
<datasource>
<servername>127.0.0.1</servername>
<serverport>3306</serverport>
<databasename>ragnarok</databasename>
<username>root</username>
<password>hackcity</password>
</datasource>
</reportenv>
[/BanUBB]
ConfigParser.java
[BanUBB]
package roadmin.Conn;
import java.util.Properties;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
class ConfigParser extends DefaultHandler {
//定义一个Properties 用来存放属性值
private Properties props;
private String currentSet;
private String currentName;
private StringBuffer currentValue = new StringBuffer();
// 构建器初始化props
public ConfigParser() {
this.props = new Properties();
}
public Properties getProps() {
return this.props;
}
// 定义开始解析元素的方法. 这里是将<xxx>中的名称xxx提取出来.
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
currentValue.delete(0, currentValue.length());
this.currentName = qName;
}
// 这里是将<xxx></xxx>之间的值加入到currentValue
public void characters(char[] ch, int start, int length) throws
SAXException {
currentValue.append(ch, start, length);
}
// 在遇到</xxx>结束后,将之前的名称和值一一对应保存在props中
public void endElement(String uri, String localName, String qName) throws
SAXException {
props.put(qName.toLowerCase(), currentValue.toString().trim());
}
}
[/BanUBB]
ParseXML.java
[BanUBB]
package roadmin.Conn;
import java.util.Properties;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
class ParseXML {
// 定义一个Properties 用来存放属性值
private Properties props;
public Properties getProps() {
return this.props;
}
public void parse(String filename) throws Exception {
// 将我们的解析器对象化
ConfigParser handler = new ConfigParser();
// 获取SAX工厂对象
SAXParserFactory factory = SAXParserFactory.newInstance();
factory.setNamespaceAware(false);
factory.setValidating(false);
// 获取SAX解析
SAXParser parser = factory.newSAXParser();
try {
// 将解析器和解析对象xml联系起来,开始解析
parser.parse(filename, handler);
// 获取解析成功后的属性
props = handler.getProps();
} finally {
factory = null;
parser = null;
handler = null;
}
}
}
[/BanUBB]
ReadConfigXml.java
[BanUBB]
package roadmin.Conn;
import java.util.Properties;
public class ReadConfigXml {
private Properties props;
public ReadConfigXml(String url) {
ParseXML myRead = new ParseXML();
try {
myRead.parse(url);
props = new Properties();
props = myRead.getProps();
} catch (Exception e) {
e.printStackTrace();
}
}
public String getServerName() {
return props.getProperty("servername");
}
public String getServerPort() {
return props.getProperty("serverport");
}
public String getDatabaseName() {
return props.getProperty("databasename");
}
public String getUserName() {
return props.getProperty("username");
}
public String getPassWord() {
return props.getProperty("password");
}
}
[/BanUBB]
DataBase.java
[BanUBB]
package roadmin.Conn;
import java.sql.*;
import roadmin.Conn.ReadConfigXml;
import javax.servlet.ServletContext;
public class DataBase {
private Connection Conn;
public DataBase() {
}
public static DataBase newInstance() {
return new DataBase();
}
public Connection getConn() {
ReadConfigXml xml = new ReadConfigXml("../RoAdmin/WEB-INF/classes/mysqlConfig.xml");
String dbhost = xml.getServerName();
String dbName = xml.getDatabaseName();
String dbUser = xml.getUserName();
String dbPass = xml.getPassWord();
String dbDriver = "org.gjt.mm.mysql.Driver";
String dbURL = "jdbc:mysql://" + dbhost + "/" + dbName + "?user="
+ dbUser + "&password=" + dbPass
+ "&autoRec&failOverRead";
try {
Class.forName(dbDriver);
Conn = DriverManager.getConnection(dbURL);
} catch (SQLException ex) {
ex.printStackTrace();
} catch (ClassNotFoundException ex1) {
ex1.printStackTrace();
}
return Conn;
}
}
[/BanUBB]
#8
补充一下:ReadConfigXml.java 和 DataBase.java 是我自己被充的.前面两个类是网上流传的...
#1
我顶起来...拜托哪位前辈为我解决一下...
#2
感觉应该差不多吧...你也应该在事先在XML文档中写好连接数据库所使用的参数..
然后在应用程序中通过DOM/JDOM/SAX等读取XML文档中的数据来连接数据库
然后在应用程序中通过DOM/JDOM/SAX等读取XML文档中的数据来连接数据库
#3
想法是好的,在SPRING框架中可以很好的实现
#4
好了.我解决了~~
真TNND是个麻烦的问题...
从网上找了一堆不完整的代码,东拼西凑.总算完成了我的想法...
稍后我把总结出来的经验和源代码贴上来...
这可真TNND是个麻烦东西....
真TNND是个麻烦的问题...
从网上找了一堆不完整的代码,东拼西凑.总算完成了我的想法...
稍后我把总结出来的经验和源代码贴上来...
这可真TNND是个麻烦东西....
#5
将数据库链接的那些参数写入固定格式的XML文件,然后运行程序时候读XML,后台拼接字符串
我做过一个类似的,至少是可行的
我做过一个类似的,至少是可行的
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
import javax.xml.parsers.*;
import javax.xml.transform.*;
import org.w3c.dom.*;
import org.xml.sax.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
public class CreateXMLForEnterServelet extends HttpServlet {
private static final String CONTENT_TYPE = "text/html; charset=GBK";
//Initialize global variables
public void init() throws ServletException {
}
//Process the HTTP Get request
public void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
response.setContentType(CONTENT_TYPE);
PrintWriter out = response.getWriter();
//获取传递过来的值
String databaseType = request.getParameter("select");
String userName = request.getParameter("userName");
String userPassword = request.getParameter("userPassword");
String dbName = request.getParameter("dbName");
String dbSouse = request.getParameter("dbSouces");
int port = Integer.parseInt(request.getParameter("portNum"));
Document doc;
Element root;
try
{
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
String path = request.getRealPath("/");
File file = new File( path + "/" + "DBInfo.xml");
if(!file.exists())
{
doc = db.newDocument();
root = doc.createElement("DBInfo");
doc.appendChild(root);
}
else
{
doc = db.parse(file);
root = doc.getDocumentElement();
}
//添加子节点
Element rowNode = doc.createElement(databaseType);
root.appendChild(rowNode);
Node node = doc.createElement("Driver");
Node nodestr = doc.createElement("ConnectString");
Node serverName = doc.createElement("ServerName");
Node nodeName = doc.createElement("UserName");
Node nodePWD = doc.createElement("PassWord");
Node nodePort = doc.createElement("Port");
Node nodeDB = doc.createElement("DataBase");
rowNode.appendChild(node);
rowNode.appendChild(nodestr);
rowNode.appendChild(serverName);
rowNode.appendChild(nodeDB);
rowNode.appendChild(nodeName);
rowNode.appendChild(nodePWD);
rowNode.appendChild(nodePort);
String nodeValue;//Driver
String nodeConStr;//连接字符串
if(databaseType.equals("ORACLE"))
{
nodeValue = "oracle.jdbc.driver.OracleDriver";
nodeConStr = "jdbc:oracle:thin";
}
else
{
nodeValue = "com.microsoft.jdbc.sqlserver.SQLServerDriver";
nodeConStr = "jdbc:microsoft:sqlserver";
}
Text text = doc.createTextNode(nodeValue);
Text textstr = doc.createTextNode(nodeConStr);
Text textName = doc.createTextNode(userName);
Text textPWD = doc.createTextNode(userPassword);
Text textServer = doc.createTextNode(dbName);
Text textPort = doc.createTextNode(String.valueOf(port));
Text textDB = doc.createTextNode(dbSouse);
node.appendChild(text);
nodestr.appendChild(textstr);
nodeName.appendChild(textName);
nodePWD.appendChild(textPWD);
serverName.appendChild(textServer);
nodePort.appendChild(textPort);
nodeDB.appendChild(textDB);
DOMSource doms = new DOMSource(doc);
StreamResult sr = null;
TransformerFactory tff = TransformerFactory.newInstance();
Transformer tf = tff.newTransformer();
sr = new StreamResult(file);
tf.transform(doms,sr);
out.println("<h1>Create XMLFile Is Ok!!</h1>");
request.getRequestDispatcher("index.jsp").forward(request,response);
}
catch(Exception ex)
{
out.println("<h1>生成 XML 配置文件时出现错误:</h1><br/><h4>"+ex+"</h4>");
out.println("<br/><br/>");
out.print("<a href='index.jsp'>【点这里回到首页】</a>");
}
out.close();
}
//Process the HTTP Post request
public void doPost(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
doGet(request, response);
}
//Clean up resources
public void destroy() {
}
}
#6
楼上的,强!
不过你这样写也还是只限于Oracle 和 MSSQL , 其实你更应该读个已经存在的XML,自己写个DTD文件来固定格式,这样才是真正意义的扩展,可以添加任意类型的DB。不过现在Spring已经解决了
不过你这样写也还是只限于Oracle 和 MSSQL , 其实你更应该读个已经存在的XML,自己写个DTD文件来固定格式,这样才是真正意义的扩展,可以添加任意类型的DB。不过现在Spring已经解决了
#7
我解决了...我用JBULIDER 2006写的...
我的代码如下:
mysqlConfig.xml
ConfigParser.java
ParseXML.java
ReadConfigXml.java
DataBase.java
我的代码如下:
mysqlConfig.xml
[BanUBB]
<?xml version="1.0" encoding="UTF-8"?>
<!--
自行修改下列参数!
servername --> 服务器名称或地址
serverport --> 服务器端口
databasename --> 数据库名
username --> 数据库帐号
password --> 数据库密码
-->
<reportenv>
<datasource>
<servername>127.0.0.1</servername>
<serverport>3306</serverport>
<databasename>ragnarok</databasename>
<username>root</username>
<password>hackcity</password>
</datasource>
</reportenv>
[/BanUBB]
ConfigParser.java
[BanUBB]
package roadmin.Conn;
import java.util.Properties;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
class ConfigParser extends DefaultHandler {
//定义一个Properties 用来存放属性值
private Properties props;
private String currentSet;
private String currentName;
private StringBuffer currentValue = new StringBuffer();
// 构建器初始化props
public ConfigParser() {
this.props = new Properties();
}
public Properties getProps() {
return this.props;
}
// 定义开始解析元素的方法. 这里是将<xxx>中的名称xxx提取出来.
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
currentValue.delete(0, currentValue.length());
this.currentName = qName;
}
// 这里是将<xxx></xxx>之间的值加入到currentValue
public void characters(char[] ch, int start, int length) throws
SAXException {
currentValue.append(ch, start, length);
}
// 在遇到</xxx>结束后,将之前的名称和值一一对应保存在props中
public void endElement(String uri, String localName, String qName) throws
SAXException {
props.put(qName.toLowerCase(), currentValue.toString().trim());
}
}
[/BanUBB]
ParseXML.java
[BanUBB]
package roadmin.Conn;
import java.util.Properties;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
class ParseXML {
// 定义一个Properties 用来存放属性值
private Properties props;
public Properties getProps() {
return this.props;
}
public void parse(String filename) throws Exception {
// 将我们的解析器对象化
ConfigParser handler = new ConfigParser();
// 获取SAX工厂对象
SAXParserFactory factory = SAXParserFactory.newInstance();
factory.setNamespaceAware(false);
factory.setValidating(false);
// 获取SAX解析
SAXParser parser = factory.newSAXParser();
try {
// 将解析器和解析对象xml联系起来,开始解析
parser.parse(filename, handler);
// 获取解析成功后的属性
props = handler.getProps();
} finally {
factory = null;
parser = null;
handler = null;
}
}
}
[/BanUBB]
ReadConfigXml.java
[BanUBB]
package roadmin.Conn;
import java.util.Properties;
public class ReadConfigXml {
private Properties props;
public ReadConfigXml(String url) {
ParseXML myRead = new ParseXML();
try {
myRead.parse(url);
props = new Properties();
props = myRead.getProps();
} catch (Exception e) {
e.printStackTrace();
}
}
public String getServerName() {
return props.getProperty("servername");
}
public String getServerPort() {
return props.getProperty("serverport");
}
public String getDatabaseName() {
return props.getProperty("databasename");
}
public String getUserName() {
return props.getProperty("username");
}
public String getPassWord() {
return props.getProperty("password");
}
}
[/BanUBB]
DataBase.java
[BanUBB]
package roadmin.Conn;
import java.sql.*;
import roadmin.Conn.ReadConfigXml;
import javax.servlet.ServletContext;
public class DataBase {
private Connection Conn;
public DataBase() {
}
public static DataBase newInstance() {
return new DataBase();
}
public Connection getConn() {
ReadConfigXml xml = new ReadConfigXml("../RoAdmin/WEB-INF/classes/mysqlConfig.xml");
String dbhost = xml.getServerName();
String dbName = xml.getDatabaseName();
String dbUser = xml.getUserName();
String dbPass = xml.getPassWord();
String dbDriver = "org.gjt.mm.mysql.Driver";
String dbURL = "jdbc:mysql://" + dbhost + "/" + dbName + "?user="
+ dbUser + "&password=" + dbPass
+ "&autoRec&failOverRead";
try {
Class.forName(dbDriver);
Conn = DriverManager.getConnection(dbURL);
} catch (SQLException ex) {
ex.printStackTrace();
} catch (ClassNotFoundException ex1) {
ex1.printStackTrace();
}
return Conn;
}
}
[/BanUBB]
#8
补充一下:ReadConfigXml.java 和 DataBase.java 是我自己被充的.前面两个类是网上流传的...