教你jdbc连接sql server数据库
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();
}
}
}
}
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。