java连接sql server2005数据库代码

database.properties文件

 

#此资源文件提供连接sql server2005数据库需要的信息,可以通过修改改变各项值

# 数据库的用户名
userName=sa
# 数据库的密码                                             
password=zzb19880803
#sql server 的驱动,一般不需更改                                    
driverName=com.microsoft.sqlserver.jdbc.SQLServerDriver
#自己创建的数据库名
databaseName=userInfo
#连接数据库的url                                  
url=jdbc:sqlserver://localhost:1433

 

 

连接数据库的类代码

public class DbUtil {

 private String url;           //数据库路径
 private String dataBaseName;  //自己创建的数据库名
 private String userName;      //用户名
 private String driverName;    //驱动名
 private String password;      //密码
 private Connection con=null;  //连接
 private PreparedStatement pst=null; //
 /**
  * 构造函数
  */
 public DbUtil(){
  init();
 }
 /**
  * 从资源文件中取出数据,连接数据库
  */
 public void init(){
  InputStream is=this.getClass().getResourceAsStream("/edu/sdnu/computer1/zzb/util/database.properties");
  Properties properties= new Properties();
  try {
   properties.load(is);
   this.url =(String) properties.get("url");
   this.dataBaseName=(String) properties.get("databaseName");
   this.userName =(String) properties.get("userName");
   this.driverName=(String) properties.get("driverName");
   this.password =(String) properties.get("password");
   String dbUrl=this.url+";DatabaseName="+this.dataBaseName;
      Class.forName(this.driverName);
      con=DriverManager.getConnection(dbUrl,this.userName,this.password);
      System.out.println("Connection Successful!");
  } catch (IOException e) {
   e.printStackTrace();
  }catch (ClassNotFoundException e) {
   e.printStackTrace();
  }catch (SQLException e) {
   e.printStackTrace();
  }
 }
 /**
  * 得到一个连接
  * @return
  */
 public Connection getConnection(){
  return this.con;
 }
 /**
  *
  * @param sql
  * @return
  */
 public PreparedStatement getPrepareStatement(String sql,Connection con){
  try {
   this.pst=con.prepareStatement(sql);
  } catch (SQLException e) {
   e.printStackTrace();
  }
  return this.pst;
 }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值