JDBC硬编码连接
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class JDBCConn {
public static final String DRIVER = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
public static final String URL = "jdbc:sqlserver://localhost:1433;DatabaseName=books";
public static final String USER = "sa";
public static final String PWD = "ok";
private Connection conn = null;
public Connection getConn() {
try {
Class.forName(DRIVER);
conn = DriverManager.getConnection(URL,USER,PWD);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return conn;
}
}
读取propperties配置文件连接
1.创建读取配置文件的类
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
/**
* 单列类:获取属性文件
* @author macau
*/
public class Env extends Properties {
/**
* 构造方法
*/
private Env() {
InputStream is = (InputStream) this.getClass().getResourceAsStream(
"/db.properties");//创建输出流
try {
load(is);//读取流
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
private static Env instance;//当前类实例
/**
* 获得当前实例
* @return
*/
public static Env getInstance() {
if (instance == null) {
makeInstance();
}
return instance;
}
/**
* 创建当前类实例
*/
private static synchronized void makeInstance() {
if (instance == null) {
instance = new Env();
}
}
}
2.通过读取配置文件的类获取数据库连接参数
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class PropConn {
private String driver = Env.getInstance().getProperty("driver");
private String url = Env.getInstance().getProperty("url");
private String user = Env.getInstance().getProperty("user");
private String pwd = Env.getInstance().getProperty("pwd");
private Connection conn = null;
public Connection getConn(){
try {
Class.forName(driver);
conn = DriverManager.getConnection(url,user,pwd);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return conn;
}
}
配置JNDI获取
1.在Tomcat安装目录的conf目录下的context.xml文件的标记中添加配置
maxActive="1000" maxIdel="30" maxWait="10000"
username="sa" password="ok"
driverClassName="com.microsoft.sqlserver.jdbc.SQLServerDriver"
url="jdbc:sqlserver://localhost:1433;DatabaseName=books" />
2.编码获取数据库连接
import java.sql.Connection;
import java.sql.SQLException;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
public class JNDIConn {
private Connection conn = null;
public Connection getConn() {
try {
Context context = new InitialContext();
DataSource source = (DataSource) context
.lookup("java:comp/env/jdbc/books");
conn = source.getConnection();
} catch (NamingException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return conn;
}
}