教你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=""; //登陆密码
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();
}
}
}
}
喜欢这样文章的可以关注我,我会持续更新,你们的关注是我更新的动力!需要更多java学习资料的也可以私信我!
祝关注我的人都:身体健康,财源广进,福如东海,寿比南山,早生贵子,从不掉发!