我用的是SQLserver
驱动加载没问图
但是连接数据库的时候出了问题
报错如下:
Communications link failure
The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
代码如下:
public class DBCon {
public static final String DRIVER="com.mysql.jdbc.Driver";
public static final String URL="jdbc:mysql://localhost:1433/工资管理系统";
public static final String USER="sa";
public static final String PWD="root";
private Connection con;
private PreparedStatement ps;
private ResultSet rs;
public DBCon(){
try {
//加载驱动程序
Class.forName(DRIVER);
System.out.println("数据库驱动加载成功");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
/**
* @return返回数据库连接
*/
public Connection getCon(){
try {
con=DriverManager.getConnection(URL, USER, PWD);
if(con!=null){
System.out.println("数据库连接成功");
}
} catch (SQLException e) {
System.out.println("数据库连接失败");
// TODO Auto-generated catch block
e.printStackTrace();
}
return con;
}
/**
* 关闭资源
*/
public void closeAll(){
if(rs!=null){
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(ps!=null)
try {
ps.close();
} catch (SQLException e) {
e.printStackTrace();
}
if(con!=null)
try {
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
public int update(String sql,Object... pras){
int resu=0;
con=getCon();
try {
ps=con.prepareStatement(sql);
if(pras!=null){
for(int i=0;i<pras.length;i++){
ps.setObject(i+1, pras[i]);
}
}
resu=ps.executeUpdate();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
closeAll();
}
return resu;
}
/**
* @param sql sql语句
* @param pras
* @return 结果集
*/
public ResultSet query(String sql,Object... pras){
con=getCon();
try {
ps=con.prepareStatement(sql);
if(pras!=null){
for(int i=0;i<pras.length;i++){
ps.setObject(i+1, pras[i]);
}
}
rs=ps.executeQuery();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return rs;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
DBCon con = new DBCon();
con.getCon();
}
}