1.导入jar包,添加依赖//DatabaseName是表名字 需要打开数据库的TCP/IP协议的端口,打开后一般默认的//端//口号是14332. String url="jdbc:sqlserver://localhost:1433; DatabaseName=webapp";//使用server management studio登录时要使用sql server身份验证,登录时的账号密码请牢记 String account = "you account";String pwd = "you password";String driver="com.microsoft.sqlserver.jdbc.SQLServerDriver";String sql = "select id,name,phone from Member_Info";public List getConnection(){List users = new ArrayList();Statement statement = null;;Connection connection = null;ResultSet set = null;try {//加载驱动Class.forName(driver);} catch (ClassNotFoundException e) {// TODO Auto-generated catch blocke.printStackTrace();}try {//创建连接connection = DriverManager.getConnection(url,account,pwd);connection.setAutoCommit(true);System.out.println("已经连接到数据库...");//创建数据库连接对象statement = connection.createStatement();//执行命令 set = statement.executeQuery(sql);User user = null;//处理结果while(set.next()){//}} catch (SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();}//由内及外关闭相应的流 if(set!=null){try {set.close();} catch (SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();}}if(statement!=null){try {statement.close();} catch (SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();}}if(connection!=null){try {connection.close();} catch (SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();}}return users;}
jdbc连接sqlserver数据库
最新推荐文章于 2024-06-30 02:15:42 发布