RELATEED CONSULTING
相关咨询
选择下列产品马上在线沟通
服务时间:9:30-18:00
你可能遇到了下面的问题
关闭右侧工具栏
struts连接数据库
  • 作者:xiaoxiao
  • 发表时间:2020-12-23 11:01
  • 来源:未知

struts-config.xml添加

在<struts-config>里面加上        <!-- ========== Data Source Configuration =============================== -->    <data-sources>        <data-source key="org.apache.struts.action.DATA_SOURCE" type="org.apache.struts.util.GenericDataSource">            <set-property property="password" value="shiwtshiwt" />            <set-property property="minCount" value="" />            <set-property property="maxCount" value="" />            <set-property property="user" value="swt" />            <set-property property="driverClass" value="org.gjt.mm.mysql.Driver" />            <set-property property="description" value="" />            <set-property property="url" value="jdbc:mysql://localhost:3306/smsgroup?autoReconnect=true" />            <set-property property="readOnly" value="false" />            <set-property property="autoCommit" value="false" />            <set-property property="loginTimeout" value="" />        </data-source>    </data-sources>

在你的Action类的excute即可执行以下连接数据库代码

import javax.servlet.ServletContext;import javax.sql.*;   

Connection conn = null;   Statement stmt = null;   ResultSet rs = null;   String tel = "tel";   ServletContext context = this.servlet.getServletContext();   DataSource dataSource = (DataSource)context.getAttribute("org.apache.struts.action.DATA_SOURCE");     try {    conn = dataSource.getConnection();    stmt = conn.createStatement();    //rs = stmt.executeQuery("select * from user where age = 24");          rs = stmt.executeQuery("select * from c_13760827783 where id = 6");    if( rs.next() ){     tel = rs.getString("name");     System.out.print(tel);    }   }catch (SQLException e) {    System.err.println(e.getMessage());   }