Connection ct = null;
Statement st = null;
try {
try {//以sqlserver数据库为例
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
} catch (ClassNotFoundException e) {
System.out.println("找不到SQLServer数据库连接驱动!");
e.printStackTrace();
}
// 得到连接
ct = DriverManager.getConnection(
"jdbc:sqlserver://IP:端口;DatabaseName=数据库名字;"
,"数据库用户"
,"数据库用户密码"
);
// 得到操作数据库sql语句的对象Statement
st = ct.createStatement();
// 执行----查询
ResultSet rs = st.executeQuery(" SQL语句 ");
//
while (rs.next()) {
Object ob0 = rs.getObject(0)==null?"":rs.getObject(0);
Object ob1 = rs.getObject(1)==null?"":rs.getObject(1);
Object ob2 = rs.getObject(2)==null?"":rs.getObject(2);
//看下取出的数据
System.out.println("---ob0--"+ob0+"---ob1---"+ob1+"---ob2---"+ob2);
}
// 关闭资源
rs.close();
} catch (SQLException e) {
System.out.println("导入失败!");
e.printStackTrace();
} finally{
if(null != st){
try {
st.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(null != ct){
try {
ct.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}