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; }}