SQL Query / Insert Builder

I am making a Java program to access / update a database via JDBC. I need to make string queries like this:
db.update(
"INSERT INTO sample_table(str_col,num_col) VALUES('Ford', 100)");
The query above is simple, but you can see how assembling the query made out of constant string fragments and variables that my program updates can become more complicated. For example, I need to also store a date. Is there a utility similar to StringBuilder for building strings that can make this process easier? I am looking for a function specifically to build SQL queries. It might look something like this:
querybuilder.insert(<table>, <name1>, <value1>, <name2>, <value2>....<nameN>, <valueN>);
Where table is the name of the table that I would be inserting into and name is the column name of the table, value would be the value to be stored under the column name. Are there SQL functions for this?

I made such a library myself (called it an SQLFormatter), but haven't put it on the web because I've not thought there would be a general interest in it. Essentially, I can create an Insert Into statement like this:
SQLFormatter formatter = SQLFormatter.get(myStatement);
String sql = formatter.createInsertIntoStatement("MyTable", new String[] {"Field1", "Field2", "Field3"}, new Object[] {value1, value2, value3});I'd be happy to share it with you, but I'm not sure about how I can make it reach you. Do I need to post it on a web site?

Similar Messages

  • Sql query to build average value

    I'm trying to build a query capture the below information. Any help is really appreciated.
    Table looks something like below.
    Room
    Subject
    Students
    A1
    Science
    10
    A1
    Maths
    20
    B1
    Science
    15
    B2
    English
    25
    C1
    Deutsch
    20
    A1
    French
    15
    C1
    English
    10
    How can i write a query so that i takes the average of students in each room and display the output? I need to write a query so that it also picks up any new rooms and students added.
    Average is sum of total students in room by number of times each room is specified.
    eg: A1 is listed 3 times a the result would be 10+20+15 divived by 3.
    A1    B1    B2    C1
    15    15    20    15
    Thanks You
    KK

    This is called pivot. And you need to know all rooms upfront. Anyway, assuming you are on 11G:
    SQL> with t as (
      2             select 'A1' room,'Science' subject,10 students from dual union all
      3             select 'A1','Maths',20 from dual union all
      4             select 'B1','Science',15 from dual union all
      5             select 'B2','English',25 from dual union all
      6             select 'C1','Deutsch',20 from dual union all
      7             select 'A1','French',15 from dual union all
      8             select 'C1','English',10 from dual
      9            )
    10  select  "'A1'_X" A1,
    11          "'B1'_X" B1,
    12          "'B2'_X" B2,
    13          "'C1'_X" C1
    14    from  t
    15    pivot(
    16          avg(students) x,
    17          max(subject) y
    18          for room in ('A1','B1','B2','C1')
    19         )
    20  /
            A1         B1         B2         C1
            15         15         25         15
    SQL>
    SY.

  • Access SQL Query - INSERT Help!

    Hi,
    I'm trying to do a simple INSERT statement in an Access Database.
    My code is:
    public SQLConnect() {
              // SQL Connection Part
              try {
                   Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); //have tried with .newInstance() as well but same effect
                   String filename = "C://Maxi//maxi.mdb";
                   String database = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=";
                   database += filename.trim() + ";DriverID=22;READONLY=true}";
                   Connection con = DriverManager.getConnection(database, "", "");               
                   PreparedStatement ps = con.prepareStatement("INSERT INTO Student (ID,FamilyName,FirstName,OtherName,Email,Phone,DOB,CourseType,Sex) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)");
                   ps.setString(1, "071111114");
                   ps.setString(2, "Crane");
                   ps.setString(3, "Frasier");
                   ps.setString(4, "Winslow");
                   ps.setString(5, "[email protected]");
                   ps.setString(6, "012345");
                   ps.setString(7, "01/01/2008");
                   ps.setString(8, "M");
                   ps.setString(9, "M");
                   ps.executeUpdate();
                   //Statement t = con.createStatement();
                   //t.execute("SELECT * FROM STUDENT");
                   //con.close();
              } catch (Exception e) {
                   System.out.println("ERROR!");
                   e.printStackTrace();
         }I am experiencing weird behaviour with the INSERT command being carried out successfully.
    The code as above will not INSERT the data in the PreparedStatement.
    However if I use any of the two methods in the commented out code, the INSERT will be carried out. Why is this happening? Surely it should just INSERT the data with the line ps.executeUpdate() without having to wait for any further commands.
    The reason I don't want to close the connection is that I am attempting to make a class so I can do simple INSERT, UPDATE and SELECT queries without having to go through the initial connection steps each time. I have read that opening and closing a connection for each query takes a lot of overhead, but it seems to be the only way this will properly execute.
    I am welcome to any suggestions.
    Cheers.

    Ha it always seems to fix itself as soon as you post about it.
    It would look as if when creating the connection if you do:
    con.setAutoCommit(false);and then after the ps.executeUpdate(); if you commit with:
    con.commit();this actually works.
    If you omit to set the AutoCommit then this does not work. I am still stumped as to why I have to do this. Any explanations?
    Edited by: adamuk on Mar 15, 2008 10:19 PM

  • During SQL query inserting a record - will it appear on the query result

    Hi,
    Oracle 10g SELECT-query executes ca 10 seconds and contains Joins over multiple tables in on database conenction.
    On execution 3rd second a new record is inserted in another database connection and commited to the database, the 3rd query satisgy the SELECT-Query fileters.
    Wil lthe inserted record on 3rd second appear on the query results?
    Thx.

    CharlesRoos wrote:
    Hi,
    Oracle 10g SELECT-query executes ca 10 seconds and contains Joins over multiple tables in on database conenction.
    On execution 3rd second a new record is inserted in another database connection and commited to the database, the 3rd query satisgy the SELECT-Query fileters.
    Wil lthe inserted record on 3rd second appear on the query results?
    Thx.In general Keith is right and a select will not see changes done and committed in a different session, that happend during the select. This is called READ CONSISTENCY. THis means a select will see the data from the exact time when it was called.
    However with database links in place read consistency can not be fully garanteed.
    See this explaination and solution from the 10g docs : http://docs.oracle.com/cd/B19306_01/server.102/b14231/ds_txnman.htm#i1008473

  • SQL query to build search form

    I have a table Department, with primary key DeptId.
    Table: Department
    DeptId Text
    1 xx
    2 yy
    3 zz
    I have another table Person, with key (not primary, and not unique) PersonId, and foreign key DeptId
    Table: Person
    PersonId DeptId
    10 1
    11 1
    11 2
    12 2
    I want to build a search form, with search fields PersonId and DeptId, so that in the resulting table, some rows from the Department table are returned. It should obey the following:
    - If both PersonId and DeptId are selected, and there is a row in the table Person that matches the selection, the row from the Department table should be returned.
    - If only PersonId is selected, any row in Department table that matches a DeptId corresponding to that PersonId should be returned.
    - If only DeptId is selected, return that row from Department exactly once (even if that DeptId doesn't appear in Person table, like DeptId 3 in this example)
    - If neither is selected, return all rows from Department
    I'm using JDeveloper 11.1.2.2.0.
    Thanks,
    Zach

    Hi Navaneeth,
    Taking the example from your link:
    SELECT org.org_id, org.name FROM organisations org WHERE EXISTS
    (SELECT 1 FROM events evt WHERE evt.org_id = org.org_id
    AND evt.contact_name = 'Eddie Harris')
    Let's say I make evt.contact_name a dropdown list, and when I query it, I leave it unselected. Would it return org.org_id, org.name from a row that has no corresponding event row?

  • Whats wrong with the sql query insert .... plz tell me

    {
    String sql = "INSERT INTO candidate VALUES (";
    sql += candidate.getEnrollmentNumber() + ",";
    sql += candidate.getDateOfEnrollment() + ",";
    sql += candidate.getName() + ",";
    sql += candidate.getContactNumber() + ",";
    sql += candidate.getGender() + ",";
    sql += candidate.getMailingAddress() + ",";
    sql += candidate.getEmailId() +",";
    sql += candidate.getClassOfVehicle() + ",";
    sql += candidate.getTypeOfVehicle() + ",";
    sql += candidate.getDateOfBirth() + ",";
    sql += candidate.getBatchTime() +")";
    System.out.println("sql: " +sql);
    //executeQuery(sql);
    executeUpdate(sql);
    }catch(SQLException e){
    e.printStackTrace();
    Giving me error as " com.mysql.jdbc.exceptions.MySQLSyntaxErrorException: You have an error in your SQL syntax;

    If you are inserting a string into your sql, you need to put it in single quotes (but not numbers).
    Example:
    sql += " ' "+candidate.getFirstName() " ', "
    Additionally, if firstName contains a single quote, it needs to be escaped by converting it to two single quotes.
    Note you don't have to do any of this if you use preparedStatements.
    Note: remove both spaces in " ' " so you get "'" in the above example, otherwise you are inserting spaces into your value.
    I use " ' " so you can more easily see what I did..

  • CPU Usage by a sql query/insert

    Hi,
    I want to know in which cases, a sql statement uses a lot of CPU usages and what are the wayouts to prevent 90-100% CPU usage.
    Thanks
    Deepak

    Of course it will! If you're doing your Select statement on production, then you will get an accurate representation of what the CPU does on production!
    However, be aware that it is production, and that anything you do could cause performance problems to the rest of the database (we once had a developer who caused massive performance problems in prod, just from running a single select statement, although I forget why it caused the problems now *{:-( )                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • Issue in creation of group in oim database through sql query.

    hi guys,
    i am trying to create a group in oim database through sql query:
    insert into ugp(ugp_key,ugp_name,ugp_create,ugp_update,ugp_createby,ugp_updateby,)values(786,'dbrole','09-jul-12','09-jul-12',1,1);
    it is inserting the group in ugp table but it is not showing in admin console.
    After that i also tried with this query:
    insert into gpp(ugp_key,gpp_ugp_key,gpp_write,gpp_delete,gpp_create,gpp_createby,gpp_update,gpp_updateby)values(786,1,1,1,'09-jul-12',1,'09-jul-12',1);
    After that i tried with this query.but still no use.
    and i also tried to assign a user to the group through query:
    insert into usg(ugp_key,usr_key,usg_priority,usg_create,usg_update,usg_createby,usg_updateby)values(4,81,1,'09-jul-12','09-jul-12',1,1);
    But still the same problem.it is inserting in db.but not listing in admin console.
    thanks,
    hanuman.

    Hanuman Thota wrote:
    hi vladimir,
    i didn't find this 'ugp_seq'.is this a table or column?where is it?
    It is a sequence.
    See here for details on oracle sequences:
    http://www.techonthenet.com/oracle/sequences.php
    Most of the OIM database schema is created with the following script, located in the RCU distribution:
    $RCU_HOME/rcu/integration/oim/sql/xell.sql
    there you'll find plenty of sequence creation directives like:
    create sequence UGP_SEQ
    increment by 1
    start with 1
    cache 20
    to create a sequence, and
    INSERT INTO UGP (UGP_KEY, UGP_NAME, UGP_UPDATEBY, UGP_UPDATE, UGP_CREATEBY, UGP_CREATE,UGP_ROWVER, UGP_DATA_LEVEL, UGP_ROLE_CATEGORY_KEY, UGP_ROLE_OWNER_KEY, UGP_DISPLAY_NAME, UGP_ROLENAME, UGP_DESCRIPTION, UGP_NAMESPACE)
    VALUES (ugp_seq.nextval,'SYSTEM ADMINISTRATORS', sysadmUsrKey , SYSDATE,sysadmUsrKey , SYSDATE, hextoraw('0000000000000000'), 1, roleCategoryKey, sysadmUsrKey, 'SYSTEM ADMINISTRATORS', 'SYSTEM ADMINISTRATORS', 'System Administrator role for OIM', 'Default');
    as a sequence usage example.
    Regards,
    Vladimir

  • Lookup vo based on sql query or on Entity?

    Hello all,
    which is better for performance to build a view object to be used as lookup [LOV] based on SQL query or build an Entity object and a view object based on it? and why?
    regards,

    As fas as i know,EO is better rather than SQL because result is backedup by EO cache..

  • Send SQL query or call stored procedure, which is best???

    hello experts!!
    i would like to ask what will be the best implementation on querying a database using Java, send a SQL query(insert into table values...) or call stored procedure(just pass parameters)?? and also in stored procedure does "autoCommit/rollback" applies/make sense??

    I searched google for this:
    Stored Procedures vs. SQL
    and found this useful link:
    http://www.karlkatzke.com/stored-procedures-vs-sql-calls/
    I thiink you should also read up on other articles based on such google searches
    to get other opinions. Also, read the links provided by that article.
    Personnally, I think stored procedures should be avoided unless there is a definite
    advantage as specified in the above article. Especially not used for CRUD operations.
    Also, no matter where you put the SQL, it should be documented. I've seen too many stored procedures that aren't documented.

  • Single SQL query

    can a single SQL query insert data into 2 different table ?
    means i would like have something like
    String sql=INSERT  TABLE1 (value1) AND INSERT TABLE 2 (value 2)  // only one queryi know its wrong...but any good way ? bcoz i dont want create 2 sql query, 2 statement etc.
    is it possible ?

    Why you dont want to create 2 sql statementbcoz do not like to make 2 statements, 2 close statements......just it looks bad.
    well ok, if there is no other compact way then i will do that.
    As java-Ang asks, why do you want to do this? i want to insert into 2 different table that means i need 2 sql query . i was thinking if there is any short cut way to achieve this.
    thanks for the time

  • Build a sql query fro different table and insert into a table

    Hi I have a requirement ,
    i have some table 1 table which holds rules which rules i have to apply on the sql query
    2 table will hold table name and column name and transformation
    with these help of 2 tables i want to build a sql quey and the sql query need to be insert into another  table.

    Hi Karthick,
    I am not going to build Dynamic Data Model.
    i already have table 1 contains rules let's say COUNT,
    and another table contain source table name , column name , Target table name, Source Table name like that
    so with the help of these 2 tables i want to build Sql query and going to insert into 3rd table.

  • How to include lexical parameters in IN string in SQL QUERY BUILDER ?

    Hi,
    I have to write an SQL Query in SQL QUERY BUILDER in Reports 6i to retrieve all details pertaining to donor codes i insert randomnly at runtime.
    The Statement is like this
    SELECT TITLE_TAB.TITLE_CODE,DONOR_TAB.DONOR_CODE, DONOR_TAB.FIRST_NAME,DONOR_TAB.MIDDLE_NAME,DONOR_TAB.LAST_NAME,CITY_MASTER_TAB.CITY_CODE FROM DONOR_TAB,CITY_MASTER_TAB,TITLE_TAB
    WHERE DONOR_CODE IN (1,2,6,70,....)
    I cannot use lexical parameter '&' in SQL QUERY BUILDER as i have to use bind variable donor_code.
    How do i do it?

    How do i do that? Can you give me an example of how i can go about with it?

  • Tool for visually building an SQL query?

    Hello,
    Can anybody recommend a good tool that allows building an Oracle SQL query through a visual interface (similar to MS Access query builder)?
    I checked Oracle SQL Developer (from Oracle) but apparently it only allows building SELECT queries visually, I need to be able to create UPDATE and INSERT statements as well...
    Thank you,
    M.R.

    I'm not very clear on what you want or what you are trying to 'simulate'.
    If you are looking for a way to "build a gui" that allows you to simultaneously modify multiple rows of data in a table:
    This sounds like a "tabular form" in Oracle APEX (which is free with all editions of Oracle including the free XE edition. )
    URL for the out-of-the-box sample "application" that demonstrates a Tabular Form for modifying the EMP table:
    https://apex.oracle.com/pls/apex/f?p=71793:4
    name/password:  demo/demo
    Feel free to sign up for a free account to play with it.
    MK

  • Query a dataset in MS SQL Server Report Builder and get splitted output of one of the fields

    Hi experts,
    I have a dataset in MS SQL Server Report Builder containing some rows like the following:
    FIELD-1
    FIELD-2
    FIELD-3
    1
    efgh
    xjhg[R]ztazutsuz[R]9
    2
    abcd
    1234[R]abcd[R]5678
    What I need is:
    FIELD-1
    FIELD-2
    FIELD-3
    1
    efgh
    xjhg
    1
    efgh
    ztazutsuz
    1
    efgh
    9
    2
    abcd
    1234
    2
    abcd
    abcd
    2
    abcd
    5678
    Can this be done?
    I'll be very happy when one finds a solution.
    Kind regards,
    Peter

    try like this..
    Declare @ta table ([FIELD-1] int, [FIELD-2] nvarchar(100), [FIELD-3] nvarchar(100))
    insert into @ta
    select 1, 'efgh', 'xjhg[R]ztazutsuz[R]9' union all
    select 2, 'abcd', '1234[R]abcd[R]5678'
    select t.[FIELD-1],t.[FIELD-2], a.b.value('.','nvarchar(100)') as [FIELD-3] from @ta t
    Cross apply
    (select cast('<R><C>' + replace(t.[FIELD-3],'[R]','</C><C>')+ '</C></R>' as xml) as XStr ) x
    Cross apply x.xstr.nodes('R/C')a(b)
    Thanks,
    Saurabh 
    http://www.linkedin.com/in/sbhadauria http://www.experts-exchange.com/M_6313078.html

Maybe you are looking for