搜索

JDBC操作技巧

Jun 07, 2016 pm 03:29 PM
jdbc工具技巧操作数据库连接

对于纯JDBC连接数据库连接工具如下: public static final String DBDRIVER=com.microsoft.sqlserver.jdbc.SQLServerDriver; public static final String DBURL=jdbc:sqlserver://10.81.35.35:1433;databaseName=Company; public static final String DBUSER

对于纯JDBC连接数据库连接工具如下:

public static final String DBDRIVER="com.microsoft.sqlserver.jdbc.SQLServerDriver";
    public static final String DBURL="jdbc:sqlserver://10.81.35.35:1433;databaseName=Company";
    public static final String DBUSERNAMW="sa";
    public static final String DBPSD="1111111";
    private Connection conn=null;
   
    public DataBaseConnection(){
        try{
            Class.forName(DBDRIVER);
            conn=DriverManager.getConnection(DBURL,DBUSERNAMW,DBPSD);
        }catch(Exception e){
            e.printStackTrace();
        }
    }

    public Connection getConnection(){
        return this.conn ;
    }
   
    public void close() throws SQLException{
        if(this.conn!=null){
            conn.close();
        }
    }

然后我们便是采用PreparedStatement对SQL语句进行预处理,如下:
PreparedStatement pstm = null;
        String sql = "insert into Person(UserName,Password) values(?,?)";
        try {
            pstm = this.conn.prepareStatement(sql);
            pstm.setString(1, person.getUserName());
            pstm.setString(2, person.getPassword());
            int count = pstm.executeUpdate();
            if (count > 0) {
                flag = true;
            }
        } catch (Exception e) {
            throw e;
        } finally {
            try {
                pstm.close();
            } catch (Exception e) {
            }
        }

这是我们最常用的一种操作方式,可是问题就来了,我们所要操作的,必须对sql中的字段很明确,比如我们按条件来查询的时候,我们就必须对条件的字段很清楚,可是,当数据库字段增多的时候,我们所要查询的条件规则很多,是不是每一个条件,我们就要写一个方法呢?显然,这种是直接的思维,然而这样思维却增加了很多代码的冗余,又或者说是,每次变换条件或者新增条件的时候,我们都必须对方法进行修改,甚至是增加。于是乎,我们想有没有一种方式可以传递字段名称进去查询,如where ?=?

本人亲测,这种方式是不存在的,因为预处理字段的时候,PreparedStatement会自动在字符串上加引号,那此时就不能达到我们想要的效果(如想要的是where name=? 得到的却是 where 'name'=?),本人曾经在这样的问题上纠结了很久。最终找到一种破解的方式,这里借鉴了IBatis的Map传参方式。希望同行爱好者,我们除了要学会使用框架或插件,得找个时间去研究一下它的原理(源码)哦。

对于where ?=? 显然是不可取,但是对于字符串占位就可以的。例子如下:

public List<person> findByParams(Map<string object> params)
            throws Exception {
        Iterator it = params.entrySet().iterator();
        List<person> list = new ArrayList<person>();
        Person person = null;
        String key = null;
        Object value = null;
        PreparedStatement pstm = null;
        while (it.hasNext()) {
            Map.Entry<string object> entry = (Map.Entry<string object>) it
                    .next();
            key = entry.getKey();
            value = entry.getValue();
        }
      <span style="color:#FF0000;">  String sql = String.format(
                "select userid,username,password from person where %s=?", key);</span>
        pstm = this.conn.prepareStatement(sql);
        pstm.setObject(1, value);
        ResultSet rs = pstm.executeQuery();
        while(rs.next()) {
            person = new Person();
            person.setUserID(rs.getInt(1));
            person.setUserName(rs.getString(2));
            person.setPassword(rs.getString(3));
        }
        rs.close();
        pstm.close();
        return list;
    }</string></string></person></person></string></person>

哈哈 此种方式可以替代where ?=?,参照ibatis

声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
在MySQL中使用视图的局限性是什么?在MySQL中使用视图的局限性是什么?May 14, 2025 am 12:10 AM

mysqlviewshavelimitations:1)他们不使用Supportallsqloperations,限制DatamanipulationThroughViewSwithJoinSorsubqueries.2)他们canimpactperformance,尤其是withcomplexcomplexclexeriesorlargedatasets.3)

确保您的MySQL数据库:添加用户并授予特权确保您的MySQL数据库:添加用户并授予特权May 14, 2025 am 12:09 AM

porthusermanagementInmysqliscialforenhancingsEcurityAndsingsmenting效率databaseoperation.1)usecReateusertoAddusers,指定connectionsourcewith@'localhost'or@'%'。

哪些因素会影响我可以在MySQL中使用的触发器数量?哪些因素会影响我可以在MySQL中使用的触发器数量?May 14, 2025 am 12:08 AM

mysqldoes notimposeahardlimitontriggers,butacticalfactorsdeterminetheireffactective:1)serverConfiguration impactactStriggerGermanagement; 2)复杂的TriggerSincreaseSySystemsystem load; 3)largertablesslowtriggerperfermance; 4)highConconcConcrencerCancancancancanceTigrignecentign; 5); 5)

mysql:存储斑点安全吗?mysql:存储斑点安全吗?May 14, 2025 am 12:07 AM

Yes,it'ssafetostoreBLOBdatainMySQL,butconsiderthesefactors:1)StorageSpace:BLOBscanconsumesignificantspace,potentiallyincreasingcostsandslowingperformance.2)Performance:LargerrowsizesduetoBLOBsmayslowdownqueries.3)BackupandRecovery:Theseprocessescanbe

mySQL:通过PHP Web界面添加用户mySQL:通过PHP Web界面添加用户May 14, 2025 am 12:04 AM

通过PHP网页界面添加MySQL用户可以使用MySQLi扩展。步骤如下:1.连接MySQL数据库,使用MySQLi扩展。2.创建用户,使用CREATEUSER语句,并使用PASSWORD()函数加密密码。3.防止SQL注入,使用mysqli_real_escape_string()函数处理用户输入。4.为新用户分配权限,使用GRANT语句。

mysql:blob和其他无-SQL存储,有什么区别?mysql:blob和其他无-SQL存储,有什么区别?May 13, 2025 am 12:14 AM

mysql'sblobissuitableForStoringBinaryDataWithInareLationalDatabase,而alenosqloptionslikemongodb,redis和calablesolutionsoluntionsoluntionsoluntionsolundortionsolunsolunsstructureddata.blobobobsimplobissimplobisslowderperformandperformanceperformancewithlararengelitiate;

mySQL添加用户:语法,选项和安全性最佳实践mySQL添加用户:语法,选项和安全性最佳实践May 13, 2025 am 12:12 AM

toaddauserinmysql,使用:createUser'username'@'host'Indessify'password'; there'showtodoitsecurely:1)choosethehostcarecarefullytocon trolaccess.2)setResourcelimitswithoptionslikemax_queries_per_hour.3)usestrong,iniquepasswords.4)Enforcessl/tlsconnectionswith

MySQL:如何避免字符串数据类型常见错误?MySQL:如何避免字符串数据类型常见错误?May 13, 2025 am 12:09 AM

toAvoidCommonMistakeswithStringDatatatPesInMysQl,CloseStringTypenuances,chosethirtightType,andManageEngencodingAndCollat​​ionsEttingsefectery.1)usecharforfixed lengengters lengengtings,varchar forbariaible lengength,varchariable length,andtext/blobforlabforlargerdata.2 seterters seterters seterters seterters

See all articles

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

SublimeText3 Mac版

SublimeText3 Mac版

神级代码编辑软件(SublimeText3)

禅工作室 13.0.1

禅工作室 13.0.1

功能强大的PHP集成开发环境

安全考试浏览器

安全考试浏览器

Safe Exam Browser是一个安全的浏览器环境,用于安全地进行在线考试。该软件将任何计算机变成一个安全的工作站。它控制对任何实用工具的访问,并防止学生使用未经授权的资源。

SublimeText3 英文版

SublimeText3 英文版

推荐:为Win版本,支持代码提示!

PhpStorm Mac 版本

PhpStorm Mac 版本

最新(2018.2.1 )专业的PHP集成开发工具