首先加入数据库的架包下面放置的是sqlserver的一个架包

在架包上点击右键选择 Add as Library加入
然后创建一个jdbc文件写入信息
driver=com.microsoft.sqlserver.jdbc.SQLServerDriver
url=jdbc:sqlserver://localhost:1433;databaseName=JXGL;encrypt=false
uname= 写入账户
upwd= 写入密码
databaseName为连接的数据库名
让后创建一个类写入
static {
Properties properties =new Properties();
InputStream is=BaseDao.class.getClassLoader().getResourceAsStream("config/jdbc.properties");
try {
properties.load(is);
driver=properties.getProperty("driver");
url=properties.getProperty("url");
uname=properties.getProperty("uname");
upwd=properties.getProperty("upwd");
// System.out.println(driver+uname);
} catch (IOException e) {
e.printStackTrace();
}
}
public void getConnection()throws Exception{
Class.forName(driver);
conn=DriverManager.getConnection(url,uname,upwd);
}
当我们使用完数据库后需要释放数据库方法
public void closeConnection(){
try {
conn.close();
ps.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
然后在另一个类继承这个类,然后调用 这个类的getConnection方法就可以连接到数据库
public class UserDaolmpl extends BaseDao{
public User loginUser(String name){
try{
getConnection();
}catch (Exception e){
e.printStackTrace();
}finally {
closeConnection();
}
return user;
}
}