阅读更多
public class DataTransmission {
private String driver="com.microsoft.sqlserver.jdbc.SQLServerDriver";
private String uri="jdbc:sqlserver://127.0.0.1:1433;DatabaseName=test"; //地址+端口号,数据库名字
private String user="sa"; //登录名
private String password="ws@123"; //登陆密码
private final static Logger log = LoggerFactory.getLogger(DataTransmission.class);
public static void main(String args[]){
DataTransmission dt = new DataTransmission();
String sql="select * from a";
// String sql="insert into a(id) values(9002)";
dt.query(sql);
}
public Connection getConnection(){
Connection conn=null;;
try { Class.forName(driver);//加载驱动
log.info("加载驱动成功!");
conn=DriverManager.getConnection(uri,user,password);
log.info("连接数据库成功!");
}
catch(SQLException e){
log.info("SQL Server连接失败!");
}
catch(Exception e){
log.info("加载驱动失败!");
}
return conn;
}
public void query(String sql){
Connection conn=getConnection();
PreparedStatement st = null;
ResultSet rs = null;
int maxCount = 2;
try {
st = conn.prepareStatement(sql,ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);
//最大查询到第几条记录
st.setMaxRows(maxCount);
rs = st.executeQuery();
//将游标移动到第一条记录
while(rs.next()){
System.out.println(rs.getInt(1));
}
} catch (SQLException e) {
e.printStackTrace();
}
finally{
try {
if(rs!=null)
rs.close();
if(st!=null)
st.close();
if(conn!=null)
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
- sqljdbc4.jar (524.7 KB)
- 下载次数: 0