Postgres Insert query not working? - postgresql

This the code. I have mentioned where the query stops. There is no error in the console too. What could be the problem. I am using postgres database. getting data from jsp servlet and passing to dao through servlet as string. But as my db has different format i want to convert the variables to their respective types. But i first want to check whether insert query works with dummy data. It seems that every thing is working fine but code flow stops where mentioned and there is no data inserted in my db also.
public void doInsert(Connection conn, String i, String nam,String indate, String amont, String tx, String tot,String closd, String shipvia, String not) throws Exception {
ResultSet rs = null;
ResultSet rs1 = null;
Statement st=null;
Statement st1=null;
// TODO Auto-generated method stub
try{
/* String in=indate;
String reverse = new StringBuffer(in).reverse().toString();
System.out.println(reverse);
System.out.println(reverse);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-M-dd");
String dateInString = indate;
Date date = sdf.parse(dateInString);
System.out.println(date);*/
/*String it=i;
String n=nam;
String in=indate;
String a=amont;
String t=tx;
String tota=tot;
String closed=closd;
String ship_via=shipvia;
String note=not;
to_date("+date+",'YYYY-MM-DD')*/
System.out.println("came above sql");
/*to_date("+date+",'YYYY-MM-DD')*/
String sql="insert into invheader(id,invdate,client_id,amount,tax,total,closed,ship_via,note) values(100001,to_date('1963-09-01', 'YYYY-MM-DD'),100001,100.00,20.00,120.00,TRUE,'tnt','note 1')";
//"insert into invheader(id,invdate,client_id,amount,tax,total,closed,ship_via,note) values('',to_date('1963-09-01', 'YYYY-MM-DD'),"+i+","+amont+","+tx+","+tot+","+closd+","+shipvia+","+not+")";
System.out.println("after 1st query");
String sql1="insert into clients(client_id,name) values("+i+","+nam+")";
System.out.println("after 2nd query");
st =conn.createStatement();
st1 =conn.createStatement();
//Statement stmt1 = conn.createStatement();//connection to statement
System.out.println("above execute"); //<======= code stops here
rs=st.executeQuery(sql);
System.out.println("above execute1");
rs1=st1.executeQuery(sql1);
System.out.println("inserted dao");
}catch(Exception e){
e.printStackTrace();
throw e;
}
// TODO Auto-generated method stub
}
Please help me. what could be the reason?

Related

Android SQLite not returning data for given search term

I am trying to build a search interface but the SQLite database returns nothing here is the code for search function
public List<DiaryModel> searchData(String srchTerm){
List<DiaryModel> data2=new ArrayList<>();
SQLiteDatabase db1 = this.getWritableDatabase();
String sql="SELECT * FROM "+DB_TABLE+" WHERE "+KEY_HEADING+" LIKE '"+srchTerm+"%'";
Cursor cursor2 =db1.rawQuery(sql,null);
cursor2.moveToFirst();
StringBuilder stringBuffer2;
stringBuffer2 = new StringBuilder();
DiaryModel diaryModel2;
while (cursor2.moveToNext()){
diaryModel2 = new DiaryModel();
String heading = cursor2.getString(cursor2.getColumnIndexOrThrow("heading"));
String desc = cursor2.getString(cursor2.getColumnIndexOrThrow("desc_"));
diaryModel2.setHeading(heading);
diaryModel2.setDesc(desc);
stringBuffer2.append(diaryModel2);
data2.add(diaryModel2);
}
return data2;
}
but when I print everything the Database returns data, here is the code for get Data used for printing data present in Database
public List<DiaryModel> getdata(){
List<DiaryModel> data=new ArrayList<>();
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor =db.rawQuery("SELECT * FROM diary_db", null);
cursor.moveToFirst();
StringBuilder stringBuffer = new StringBuilder();
DiaryModel diaryModel;
while (cursor.moveToNext()){
diaryModel = new DiaryModel();
String heading = cursor.getString(cursor.getColumnIndexOrThrow(KEY_HEADING));
String desc = cursor.getString(cursor.getColumnIndexOrThrow(KEY_DESC));
diaryModel.setHeading(heading);
diaryModel.setDesc(desc);
stringBuffer.append(diaryModel);
data.add(diaryModel);
}
return data
}
The thing is only this SQL statement is working
SELECT * FROM diary_db
and if any condition is put nothing returns.
There is something that you are doing wrong in both methods:
cursor.moveToFirst();
and then:
while (cursor.moveToNext()){
.................
}
This way you miss the 1st row of the results, because after you move the cursor to the 1st row, you move once again to the next row.
So delete this:
cursor.moveToFirst();
from both methods.

How to insert DATE type in PostgreSql using Java?

I have a column of date type (daterecord) in PostgreSql and jdatechooser component in java (dateChooser). I am trying to insert the selected date into my database with this initial code:
Date daterec = dateChooser.getDate();
String sql= "INSERT INTO date values (?)";
pst.prepareStatement(sql);
pst.setDate(1, daterec);
pst.execute();
..but I know my setDate code is wrong..please help what to do?
i can tell you how to insert a date record into a mysql table by using the Datechooser control..it is how i do it..so it may differ from your point of view
public void getdate() {
DateFormat df=new SimpleDateFormat("yyyy-MM-dd");
String s=df.format(jDateChooser1.getDate());
jLabel1.setText(""+s);
}
public void insert(){
try{
Class.forName("java.sql.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost/<database_name>","root","<db password>");
Statement stmt=con.createStatement();
String query="insert into test values('"+jLabel1.getText()+"')";
stmt.executeUpdate(query);
JOptionPane.showMessageDialog(null,"Insert successful");
}
catch(Exception e) {
JOptionPane.showMessageDialog(null,"Error in connectivity");
}
}

MongoDB DateTime Format

In mongodb adhoc query, before executing the query, how to format the date type element to dd\mm\yyyy format and then execute the query?
I solved this by inserting the datetime as integer using the getTime() method in java.
EG:
Date dt=new Date();
long integer_date=dt.getTime();
I used the above line of code to insert date as integer.With this it was easy to fetch records between a particular date.
I asked a similar question a little while back...this might be what you're looking for: What is the syntax for Dates in MongoDB running on MongoLab?
If you are using Java, you can create Date objects from strings using the parse method of the DateFormat class.
The Java documentation on the DateFormat Class may be found here:
http://docs.oracle.com/javase/1.4.2/docs/api/java/text/DateFormat.html
The specific section on the parse method is here:
http://docs.oracle.com/javase/1.4.2/docs/api/java/text/DateFormat.html#parse%28java.lang.String%29
The Java documentation on the Date object may be found here:
http://docs.oracle.com/javase/1.4.2/docs/api/java/util/Date.html
As per the "Constructor Summary" section, the ability to pass a string into the constructor is "Deprecated. As of JDK version 1.1, replaced by DateFormat.parse(String s)."
While I was researching the above, I also came across the Calendar class, which may be used for converting a Date object and a set of integers. It may not be necessary for this application, but I thought it might be useful to include a link to the documentation:
http://docs.oracle.com/javase/1.4.2/docs/api/java/util/Calendar.html
Integers for year, month, day, hour, etcetera may be passed in via the set method:
http://docs.oracle.com/javase/1.4.2/docs/api/java/util/Calendar.html#set%28int,%20int,%20int,%20int,%20int%29
By way of example, here is a short Java Program that creates a number of Date objects, stores them in a Mongo collection, and then executes a query similar to what you have described. Hopefully it will help you to accomplish your goal. NOTE: This program drops a collection named "dates", so be sure to change the collection name if you already have such a collection in your database!
public static void main(String[] args) throws UnknownHostException, MongoException {
Mongo m = new Mongo( "localhost:27017" );
DB db = m.getDB("test");
DBCollection coll = db.getCollection("dates");
coll.drop();
DateFormat df = DateFormat.getInstance();
String dateString = new String();
Date myDate = new Date();
// Save some test documents
for(int i=1; i<11; i++){
dateString = "04/" + String.valueOf(i) + "/12 11:00 AM, EST";
BasicDBObject myObj = new BasicDBObject("_id", i);
try {
myDate = df.parse(dateString);
} catch (ParseException e) {
e.printStackTrace();
}
myObj.put("date", myDate);
System.out.println(myDate);
coll.save(myObj);
}
// Build the query
Date startDate = new Date();
Date endDate = new Date();
try {
startDate = df.parse("04/4/12 11:00 AM, EST");
endDate = df.parse("04/6/12 11:00 AM, EST");
} catch (ParseException e) {
e.printStackTrace();
}
BasicDBObject dateQuery = new BasicDBObject();
dateQuery.put("$gte", startDate);
dateQuery.put("$lte", endDate);
System.out.println("---------------");
//Execute the query
DBCursor myCursor = coll.find(new BasicDBObject("date", dateQuery));
//Print the results
while(myCursor.hasNext()){
System.out.println(myCursor.next().toString());
}
}
This is use full to format code to date format from simple date time format and the reverse steps also supporting this way to retrieve date from MongoDB.
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
Date fDate = formatter.parse((String) metaData.getValue());
newMeta.setValue(fDate);[![In this image you can see how is the save scenario process in mongoDB][1]][1]
Date class has a before(date) or after(date) method... It is easy to use: no conversion to seconds/milliseconds.
public void execute(Tuple input) {
try {
date=(Date) input.getValueByField("date");
boolean before = date.before(myDate); // compare the data retrieved with your date.
if (before) {
...
} else {
...
}
} catch (Exception e) {
logger.error("Error...", e);
}
This approach is easier than the accepted answer..

How to Count the number of rows in Sparql Query

I am working in Eclipse and am using 2 Java Files: Admin.java and SemanticSearch.java. Through the the Admin.java I am logging in and checking if the Username and Password are existing in my RDF file. The function of login in Admin.java calls SemanticSearch.java which runs a SPARQL Query. My Query is giving me the answer in Console of Eclipse and even onto another file. Now my job is to give back the answer to Admin.java either by returning the value or by counting rows and sending that value to Admin.java. With this if number of rows is 1 that means the username and password match and I can allow the user to login.
But I am not able to do so. I have tried using count(), Count() as CNT, even tried int res=results.next. But nothing seems to help.
I am pasting the code below:
Admin.java
SemanticSearch semsearch = new SemanticSearch(request.getSession());
semsearch.loadData(REALPATH + RDFDATASOURCEFILE1);
semsearch.searchForUser(response.getOutputStream(),null, userName, password);
In SemanticSearch.java
public void searchForUser(OutputStream out, String xslfile1, String userName, String password) {
String prolog = "PREFIX kb:<"+VUSER.getURI()+">";
System.out.println("Search for user in semantic search.java");
String queryString1 = prolog +"\n" +"SELECT * " +"WHERE {" +"?x kb:Uname ?username. ?x kb:Password ?password. ?x kb:Interest ?interest. " +"FILTER regex(?username, \"" +userName +"\")}";
System.out.println(queryString1);
Query query=QueryFactory.create(queryString1);
QueryExecution qexec = QueryExecutionFactory.create(query, model);
ResultSet results1 = qexec.execSelect(); --> here the two rows are printed
int res=results1.getRowNumber();
System.out.println(results1); -->here answer is 0
ResultSetFormatter.out(results1);
ResultSetFormatter.out(out, results1);
System.out.println(res);
try {
if (xslfile1 != null)
{
out.write(ResultSetFormatter.asXMLString(results1, xslfile1).getBytes("UTF-8"));
System.out.println(results1);
System.out.println(xslfile1);
System.out.println("I am in if");
}
else
{
out.write(ResultSetFormatter.asXMLString(results1).getBytes(
"UTF-8"));
System.out.println("I am in else");
}
} catch (IOException e) {
e.printStackTrace();
}
}
Please Help, I am struggling to get this from a week, Regards, Archana.
In SPARQL 1.1, which may be supported in the triplestore you're using, the syntax is:
SELECT (COUNT(*) AS ?count)
WHERE {
...
}
You should get an integer returned in the ?count column, with the number of results.

using the TSqlParser

I'm attempting to parse SQL using the TSql100Parser provided by microsoft. Right now I'm having a little trouble using it the way it seems to be intended to be used. Also, the lack of documentation doesn't help. (example: http://msdn.microsoft.com/en-us/library/microsoft.data.schema.scriptdom.sql.tsql100parser.aspx )
When I run a simple SELECT statement through the parser it returns a collection of TSqlStatements which contains a SELECT statement.
Trouble is, the TSqlSelect statement doesn't contain attributes such as a WHERE clause, even though the clause is implemented as a class. http://msdn.microsoft.com/en-us/library/microsoft.data.schema.scriptdom.sql.whereclause.aspx
The parser does recognise the WHERE clause as such, looking at the token stream.
So, my question is, am I using the parser correctly? Right now the token stream seems to be the most useful feature of the parser...
My Test project:
public static void Main(string[] args)
{
var parser = new TSql100Parser(false);
IList<ParseError> Errors;
IScriptFragment result = parser.Parse(
new StringReader("Select col from T1 where 1 = 1 group by 1;" +
"select col2 from T2;" +
"select col1 from tbl1 where id in (select id from tbl);"),
out Errors);
var Script = result as TSqlScript;
foreach (var ts in Script.Batches)
{
Console.WriteLine("new batch");
foreach (var st in ts.Statements)
{
IterateStatement(st);
}
}
}
static void IterateStatement(TSqlStatement statement)
{
Console.WriteLine("New Statement");
if (statement is SelectStatement)
{
PrintStatement(sstmnt);
}
}
Yes, you are using the parser correctly.
As Damien_The_Unbeliever points out, within the SelectStatement there is a QueryExpression property which will be a QuerySpecification object for your third select statement (with the WHERE clause).
This represents the 'real' SELECT bit of the query (whereas the outer SelectStatement object you are looking at has just got the 'WITH' clause (for CTEs), 'FOR' clause (for XML), 'ORDER BY' and other bits)
The QuerySpecification object is the object with the FromClauses, WhereClause, GroupByClause etc.
So you can get to your WHERE Clause by using:
((QuerySpecification)((SelectStatement)statement).QueryExpression).WhereClause
which has a SearchCondition property etc. etc.
Quick glance around would indicate that it contains a QueryExpression, which could be a QuerySpecification, which does have the Where clause attached to it.
if someone lands here and wants to know how to get the whole elements of a select statement the following code explain that:
QuerySpecification spec = (QuerySpecification)(((SelectStatement)st).QueryExpression);
StringBuilder sb = new StringBuilder();
sb.AppendLine("Select Elements");
foreach (var elm in spec.SelectElements)
sb.Append(((Identifier)((Column)((SelectColumn)elm).Expression).Identifiers[0]).Value);
sb.AppendLine();
sb.AppendLine("From Elements");
foreach (var elm in spec.FromClauses)
sb.Append(((SchemaObjectTableSource)elm).SchemaObject.BaseIdentifier.Value);
sb.AppendLine();
sb.AppendLine("Where Elements");
BinaryExpression binaryexp = (BinaryExpression)spec.WhereClause.SearchCondition;
sb.Append("operator is " + binaryexp.BinaryExpressionType);
if (binaryexp.FirstExpression is Column)
sb.Append(" First exp is " + ((Identifier)((Column)binaryexp.FirstExpression).Identifiers[0]).Value);
if (binaryexp.SecondExpression is Literal)
sb.Append(" Second exp is " + ((Literal)binaryexp.SecondExpression).Value);
I had to split a SELECT statement into pieces. My goal was to COUNT how many record a query will return. My first solution was to build a sub query such as
SELECT COUNT(*) FROM (select id, name from T where cat='A' order by id) as QUERY
The problem was that in this case the order clause raises the error "The ORDER BY clause is not valid in views, inline functions, derived tables, sub-queries, and common table expressions, unless TOP or FOR XML is also specified"
So I built a parser that split a SELECT statment into fragments using the TSql100Parser class.
using Microsoft.Data.Schema.ScriptDom.Sql;
using Microsoft.Data.Schema.ScriptDom;
using System.IO;
...
public class SelectParser
{
public string Parse(string sqlSelect, out string fields, out string from, out string groupby, out string where, out string having, out string orderby)
{
TSql100Parser parser = new TSql100Parser(false);
TextReader rd = new StringReader(sqlSelect);
IList<ParseError> errors;
var fragments = parser.Parse(rd, out errors);
fields = string.Empty;
from = string.Empty;
groupby = string.Empty;
where = string.Empty;
orderby = string.Empty;
having = string.Empty;
if (errors.Count > 0)
{
var retMessage = string.Empty;
foreach (var error in errors)
{
retMessage += error.Identifier + " - " + error.Message + " - position: " + error.Offset + "; ";
}
return retMessage;
}
try
{
// Extract the query assuming it is a SelectStatement
var query = ((fragments as TSqlScript).Batches[0].Statements[0] as SelectStatement).QueryExpression;
// Constructs the From clause with the optional joins
from = (query as QuerySpecification).FromClauses[0].GetString();
// Extract the where clause
where = (query as QuerySpecification).WhereClause.GetString();
// Get the field list
var fieldList = new List<string>();
foreach (var f in (query as QuerySpecification).SelectElements)
fieldList.Add((f as SelectColumn).GetString());
fields = string.Join(", ", fieldList.ToArray());
// Get The group by clause
groupby = (query as QuerySpecification).GroupByClause.GetString();
// Get the having clause of the query
having = (query as QuerySpecification).HavingClause.GetString();
// Get the order by clause
orderby = ((fragments as TSqlScript).Batches[0].Statements[0] as SelectStatement).OrderByClause.GetString();
}
catch (Exception ex)
{
return ex.ToString();
}
return string.Empty;
}
}
public static class Extension
{
/// <summary>
/// Get a string representing the SQL source fragment
/// </summary>
/// <param name="statement">The SQL Statement to get the string from, can be any derived class</param>
/// <returns>The SQL that represents the object</returns>
public static string GetString(this TSqlFragment statement)
{
string s = string.Empty;
if (statement == null) return string.Empty;
for (int i = statement.FirstTokenIndex; i <= statement.LastTokenIndex; i++)
{
s += statement.ScriptTokenStream[i].Text;
}
return s;
}
}
And to use this class simply:
string fields, from, groupby, where, having, orderby;
SelectParser selectParser = new SelectParser();
var retMessage = selectParser.Parse("SELECT * FROM T where cat='A' Order by Id desc",
out fields, out from, out groupby, out where, out having, out orderby);