2009年4月1日
第一种方法:
package jdbc;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class DBConnection {
public Connection getConnection(){
Connection conn = null;
String driverName = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
String url = "jdbc:sqlserver://localhost:1433;DatabaseName = mp";
String user = "sa";
String password = "sa";
try{
Class.forName(driverName);
conn = DriverManager.getConnection(url,user,password);
if(conn!=null){
System.out.println("ok");
}
}catch(Exception e){
e.printStackTrace();
System.out.println("false");
}
return conn;
}
public void closeConnection(Connection conn){
if(conn!=null){
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
public static void main(String args[]){
DBConnection dbc = new DBConnection();
Connection conn = null;
conn = dbc.getConnection();
}
}
第二种方法:
package jdbc;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;
public class DBConnection {
//配置文件名
private static String CONFIG_FILENAME="config.properties";
//配置文件
private Properties prop = null;
//连接数据库的驱动程序
private String driverName="";
//配置数据库的 url,拥护名和密码
private String url="";
private static String user="";
private static String password="";
/**
* 构造函数,从配置文件中获取连接数据库的信息
*/
public DBConnection(){
prop = new Properties();
//度曲文件信息
InputStream in = jdbc.DBConnection.class.getResourceAsStream("/"+CONFIG_FILENAME);
try {
prop.load(in);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//驱动程序名称
driverName = prop.getProperty("DataBaseDrivers").trim();
user = prop.getProperty("DataBaseUser");
password = prop.getProperty("DataBaseUserPassword");
url = getDBURL();
//装载驱动程序
try {
Class.forName(driverName).newInstance();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
/**
* 从属性文件中获取信息组装数据库连接的URL
*/
private String getDBURL(){
if(prop.getProperty("DataBaseType").equals("SQLServer")){
return "jdbc:sqlserver://"+prop.getProperty("DataBaseServerName")+":"+prop.getProperty("DatabaseServerPort")+";"+"SelectMode=cursor;DataBaseName="+prop.getProperty("DataBaseName");
}
return url;
}
/**
* 返回数据库连接
*/
public static Connection getConnection() throws SQLException{
return DriverManager.getConnection(user,password,user);
}
public static void main(String[] args){
Connection conn = null;
System.out.println("ok");
}
}
posted @
2009-04-01 09:25 玄风 阅读(140) |
评论 (1) |
编辑 收藏