常用公共类代码一之数据库的连接
在项目中,我们经常会写到一些公共的代码,来让开发人员调用,减少代码重复,下面,我就将一些常用到的公共类贴出来和大家分享!!
一、数据库的连接,常用的方式有直接将那些要连接的参数放到java类中、将连接参数放到Properties文件中或者放到XML文件中,下面一一为大家描述
1、直接连接:
[java]
<span style="font-size:18px;"> 普通的配置方式
public static Connection getConnection(){
Connection conn=null;
try {
Class.forName("com.mysql.jdbc.Driver");
String url="jdbc:mysql://127.0.0.1:3306/xinyuandb";
String username="root";
String password="123456";
conn=DriverManager.getConnection(url, username, password);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return conn;
}</span> www.zzzyk.com
2、通过Properties文件创建连接,好处,很灵活,不用在代码里面进行更改
创建jdbc.properties文件
driver=com.mysql.jdbc.Driver
url=jdbc\:mysql\://127.0.0.1\:3306/xinyuandb
username=root
password=123456
[java]
<span style="font-size:18px;"> 从properties文件中读取
public static Connection getConnection(){
Connection conn=null;
Properties p=new Properties();
try {
//从当前线程加载
p.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("jdbc.properties"));
Class.forName(p.getProperty("driver"));
conn=DriverManager.getConnection(p.getProperty("url"), p.getProperty("username"), p.getProperty("password"));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return conn;
}
<span style="color:#FF0000;">3、通过XML文件读取</span>
创建jdbc.xml文件
<?xml version="1.0" encoding="UTF-8"?>
<config>
<jdbc-config>
<driver>com.mysql.jdbc.Driver</driver>
<url>jdbc:mysql://127.0.0.1:3306/xinyuandb</url>
<username>root</username>
<password>123456</password>
</jdbc-config>
</config>
创建javaBean类
package com.common.db;
public class JdbcBean {
private String driver;
private String url;
private String username;
private String password;
public String getDriver() {
return driver;
}
public void setDriver(String driver) {
this.driver = driver;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
创建XML解析类
</span><pre name="code" class="java"><span style="font-size:18px;">package com.common.db;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
public class XmlConfigReader {
private static XmlConfigReader instance;
private JdbcBean bean=null;
//调用构造函数进行XML文件解析
private XmlConfigReader(){
SAXReader reader=new SAXReader();
try {
Document doc=reader.read(Thread.currentThread().getContextClassLoader().getResourceAsStream("jdbc.xml"));
Element root=doc.getRootElement();
Element first=root.element("jdbc-config");
补充:软件开发 , Java ,