简体   繁体   中英

Java setting up prepared statements

This is a question relating more to coding standards than anything else.

The problem that I am having is that I am struggling to use my prepared statements as a class/constructor (I am from an informix background btw java is still new to me).

Usually when I code I like to keep scripting out of the main block as much as possible and then call in functions as I need them like in the example I will show. I am also exaggerating the structure with lots of forward slashes.

public class Script {

    ///////////////////////////////////////////////////////////////// start main
    public static void main(String[] args) {

        System.out.println("Script Is Starting");    // basic message

        classCONN conn = new classCONN();            // connect class
        Connection cnct = null;                      // connect variable
                                                     //
        try {                                        // try connect
           conn.func_driverCheck();                  //
           cnct = conn.func_dbConnect();             //
        } catch(SQLException log) {                  //
           System.out.println(log);                  //
        }                                            //

        *i would like to call the prepare*
        *statements function once for the*
        *rest of the script*

        classSQL sql = new classSQL();               // prepare statements
        sql.func_prep(cnct);                         //

        users_sel.setString(1, "zoh");               // insert with prepared
        users_sel.setString(2, "my");                // statements
        users_sel.setString(3, "goodness");          //
        row = users_sel.executeQuery();              //

    }
    ///////////////////////////////////////////////////////////////// end main

    ///////////////////////////////////////////////////////////////// start classes
    class classCONN {

       public void func_driverCheck() {*code to check driver*}

       public Connection func_dbConnect() {*code to connect to db*}

    }

    class classSQL {

       *I would like to prepare my statements here*

       public void f_prep(Connection cnct) {
           lv_sql = "INSERT INTO users " +
                    "VALUES(?, ?, ?)";
           PreparedStatement users_ins = cnct.prepareStatement(lv_sql);
       }

    }
    ///////////////////////////////////////////////////////////////// end classes

}

so my question being is there a way to get code like this to work so that the statements are prepared and then I can executeUpdate them from inside different classes or in the main or anything like that without actually preparing the statements completely in the main block

Here you have greate Example on how to use PreparedStatement.

JDBC PreparedStatement Example – Select List Of The Records

Ok I have come up with an answer to my own question and I would just like to post it here in case anyone can benefit from it or has anything to add to it because that's what this community is for.

public class Prog {

    // static variables ---------------------------------------------------
    static Connection conn;
    static ResultSet row;

    // main ---------------------------------------------------------------
    public static void main(String[] args) {

       // connect to db ---------------------------------------------------
       try {
          DBConnect cl_conn = new DBConnect();
          conn = cl_conn.f_connect();
       } catch(Exception log) {
          System.out.println("FAIL")
       }

       // prepare statements ----------------------------------------------
       SQLPrep prep = new SQLPrep(conn);

       // execute statement 01 --------------------------------------------
       try {
          prep.users_sel.setInt(1, 2);           // pass values to stmnt
          row = prep.users_sel.executeQuery();   // execute stmnt
       } catch(SQLException log) {
          System.out.println("FAIL");
       }

    }

}

class DBConnect {
   ***code to connect to db***
}

// all prepared stmnts in one place ----------------------------------------
class SQLPrep {

   static PreparedStatement users_sel = null;    // select from users
   static PreparedStatement access_sel = null;   // select from access

   try {

      sp_sql = "SELECT * FROM USERS WHERE u_id = ?";
      users_sel = conn.prepareStatement(sp_sql);

      sp_sql = "SELECT * FROM ACCESS WHERE a_id = ?";
      access_sel = conn.prepareStatement(sp_sql);

   } catch(SQLException log) {
      System.out.println("FAIL");
   }

}

This may look strange to some people but I find this to be a very clean and tidy way of structuring code (keeping as much code out of the main as possible). Even the block where the statement is executed can be moved into a separate function and would only need to be passed 'prep.users_prep' to work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM