with statement

  • python中的with语句是用来干嘛的?有什么作用?

with语句的作用是通过某种方式简化异常处理,它是所谓的上下文管理器的一种,详情请看PEP-343
用法举例如下:

    with open('output.txt', 'w') as f:
        f.write('Hi there!')

当你要成对执行两个相关的操作的时候,这样就很方便,以上便是经典例子,with语句会在嵌套的代码执行之后,自动关闭文件。这种做法的还有另一个优势就是,无论嵌套的代码是以何种方式结束的,它都关闭文件。如果在嵌套的代码中发生异常,它能够在外部exception handler catch异常前关闭文件。如果嵌套代码有return/continue/break语句,它同样能够关闭文件。

  • 我们也能够自己构造自己的上下文管理器

我们可以用contextlib中的context manager修饰器来实现,比如可以通过以下代码暂时改变当前目录然后执行一定操作后返回。

from contextlib import contextmanager
import os

@contextmanager
def working_directory(path):
    current_dir = os.getcwd()
    os.chdir(path)
    try:
        yield
    finally:
        os.chdir(current_dir)

with working_directory("data/stuff"):
    # do something within data/stuff
# here I am back again in the original working directory

参考文献:
http://stackoverflow.com/questions/1369526/what-is-the-python-keyword-with-used-for
http://stackoverflow.com/questions/3012488/what-is-the-python-with-statement-designed-for

展开阅读全文

关于 statement 的提问

04-23

小弟刚学java,在连接数据库时出了问题。代码如下,请高手救助:rnrn<%@ page contentType="text/html; charset=gb2312" language="java" import="java.sql.*" errorPage="" %>rn<%@page import="java.util.Date"%>rn<%@page import="java.text.*"%>rnrnrn rn rnrn rn 查询记录rnrn rn rn rn rnrn<% rn String driverClass = "com.microsoft.jdbc.sqlserver.SQLServerDriver"; rn String connectUrl = "jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=words"; rn int searchnum=0;rn String keyword="";rn String way="";rn String strSQL="";rn String sqln="";rn String properties="";rn String word="";rn String fullword="";rn String chinese="";rn String inpdate="";rn String udate="";rn keyword=request.getParameter("keyword");rn way=request.getParameter("way");rn //String addr="";rn tryrn rn Class.forName(driverClass);rn rn catch(Exception e)rn rn out.println(e.getMessage());rn rn tryrn rn Connection conn=null;rn Statement st=null;rn rn conn = DriverManager.getConnection(connectUrl,"sa",""); rn st = conn.createStatement();rn strSQL="select * from words where properties=way";rn strSQL+="OR properties=way";rn strSQL+="AND word like '%"+keyword+"%'";rn // out.println(strSQL);rn sqln="select count(*) from words where properties=way";rn sqln+="OR properties=way";rn sqln+="AND word like '%"+keyword+"%'";rn // out.println(sqln);rn ResultSet rsn=st.executeQuery(sqln);rn rn while(rsn.next())rn searchnum=rsn.getInt("count(*)");rn rn // out.println(searchnum);rn rsn.close();rn rn catch(Exception ex)rn rn out.println(ex.getMessage());rn rn%>rn rn rn 单词/缩略语搜索 rn rnrn rn rn rn rn rn 搜索 -> 关键字:rn <%=keyword%>rn rn rn 共搜索到<%=searchnum%>条记录rn rn 返回 rnrn rn<%rn ResultSet rs=null; rn rs=st.executeQuery(strSQL); rn while(rs.next())rn properties=rs.getString("properties");rn word=rs.getString("word");rn fullword=rs.getString("fullword");rn chinese=rs.getString("chinese");rn inpdate=rs.getString("inpdate");rn udate=rs.getString("udate");rn //输出表格 rn out.println(" rn rn 科室 rn rn 单词/缩略语rn rn 完整单词rn rn 中文含义rn rn 输入日期rn rn 更新日期rn rn rn ");rn out.println(" "+properties+"");rn out.println(" "+word+" ");rn out.println(" "+fullword+" ");rn out.println(" "+chinese+" ");rn out.println(" "+inpdate+" ");rn out.println(" "+udate+"");rn out.println("");rn rn rs.close();rn out.println("");rn out.println("");rn //out.println("共搜索到"+searchnum+"条记录");rn%> rnrn rn rn rn rn rn rn rn rn coypright@2007 联系:bbrn 欢迎使用本系统!!!rnrnrn<%rn st.close(); rn conn.close();rn%>rnrn出现的错误是:rnrnAn error occurred at line: 108 in the jsp file: /database/words/search.jsprnst cannot be resolvedrn105: rn106: <%rn107: ResultSet rs=null; rn108: rs=st.executeQuery(strSQL); rn109: while(rs.next())rn110: properties=rs.getString("properties");rn111: word=rs.getString("word");rnrnrnAn error occurred at line: 145 in the jsp file: /database/words/search.jsprnst cannot be resolvedrn142: rn143: rn144: <%rn145: st.close(); rn146: conn.close();rn147: %>rnrnrnAn error occurred at line: 146 in the jsp file: /database/words/search.jsprnconn cannot be resolvedrn143: rn144: <%rn145: st.close(); rn146: conn.close();rn147: %>rnrn好像是statement类对象st出问题了,但是没有发现呀,郁闷一晚上了!!! 论坛

找不到statement源?

02-02

我遇到这样的一个问题,我在一个用户输入表单,输入数据,然后调用一个类的addUser方法将数据存进去(事先获取了一个conn()),接着我在后面又用一个getAllUser方法来获取所有用户信息,就出错了,我利用单步跟踪发现是statement问题,提示它的各种源都找不到,我试着改了很多地方都不行:rnrn下面是程序:rnrn<%@ page contentType="text/html; charset=gb2312" language="java" import="java.sql.*"%>rn<%@ page import="cn.db.Users"%>rnrn<%rnResultSet userRs=null;rnUsers admin=new Users();rnString name=request.getParameter("username");rnString pwd=request.getParameter("userpwd");rnString usertype=request.getParameter("utype");rnString email=request.getParameter("useremail");rnString qq=request.getParameter("userqq");rnString msn=request.getParameter("usermsn");rnadmin.setUserName(name);rnadmin.setUserPwd(pwd);rnadmin.setUserLevel(usertype);rnadmin.setUserEmail(email);rnadmin.setUserQQ(qq);rnadmin.setUserMsn(msn);rnadmin.setLastLoginIp("192.168.0.1");rnout.println("用户名:"+name+" ");rnout.println("密 码:"+pwd+" ");rnout.println("用户类型:"+usertype+" ");rnout.println("邮件:"+email+" ");rnout.println("QQ:"+qq+" ");rnout.println("MSN:"+msn+" ");rnrnif(udb.addUser(admin))rnout.println(" 恭喜您,记录插入成功!");rn%>rn rn<%rnuserRs=udb.getAllUser();rnwhile(userRs.next())rnrnout.println("aaa");rnrn%>rnrn在userRs=udb.getAllUser();这出错了.rnrn //********定义方法:添加用户*******rn public boolean addUser(Users admin) throws SQLExceptionrn rn Connection con=null;rn PreparedStatement sm=null;rn tryrn //获取连接rn con=DbConn.getConn();rn String sql="insert into Admin(UserName,UserPwd,UserLevel,UserEmail,UserQQ,UserMsn,LastLoginIp) ";rn sql=sql+"values(?,?,?,?,?,?,?)";rn sm=con.prepareStatement(sql);rn //sm.setInt(1, admin.getId());rn sm.setString(1,admin.getUserName());rn sm.setString(2,admin.getUserPwd());rn sm.setString(3,admin.getUserLevel());rn sm.setString(4,admin.getUserEmail());rn sm.setString(5,admin.getUserQQ());rn sm.setString(6,admin.getUserMsn());rn sm.setString(7,admin.getLastLoginIp());rn sm.execute();rn catch(SQLException e)rn System.err.println("Error:"+e.getMessage());rn finallyrn sm.close();rn con.close(); //关闭数据库连接rn rn return true;rn rnrn //********定义方法:获取所有用户信息*******rn public ResultSet getAllUser() throws SQLExceptionrn rn Connection con=null;rn Statement sm=null;rn ResultSet rs=null;rn tryrn //获取连接rn con=DbConn.getConn();rn sm=con.createStatement();rn String sql="select * from Admin";rn sm.executeQuery(sql);rn catch(SQLException e)rn System.err.println("Error:"+e.getMessage());rn finallyrn rn sm.close();rn con.close();rn rn return rs;rn rnrn连接类:rnrnpublic class DbConn rn private static String dbDriver="com.mysql.jdbc.Driver";rn private static String dbConnUrl="jdbc:mysql://localhost:3309/news?user=root&password=jimluck";rn private static Connection conn = null;rn private Statement stmt=null;rn ResultSet rs=null;rn private static int sign=1;rn rn public DbConn()rn rn rn rn public static Connection getConn() throws SQLException rn rn if (conn != null && !conn.isClosed())// 不为空且没关闭rn return conn;rn rn tryrn Class.forName(dbDriver);rn conn= DriverManager.getConnection(dbConnUrl);rn rn catch(java.lang.ClassNotFoundException e)rn System.err.println("Class Error:"+e.getMessage());rn rn return conn;rn rn ...rn 论坛

没有更多推荐了,返回首页