how to avoid updation of id column - sql

I don't want to update the id column because it is auto incremented .
when I run this code then i face
java.sql.SQLException: No value specified for parameter 1.
so my question is how to avoid / bypass the update.
String sql="";
sql = "insert into registration(first_name,last_name,gender,email_id,dob,"
+ "father_name,mother_name,contact,mobile,address,city,country,graduation,"
+ "graduation_marks,graduation_year,inter,inter_marks,inter_year,high_school,"
+ "high_marks,high_year,role,salary,resume,photo,pre_comp) value(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?);";
// int i=0;
PreparedStatement p = con.prepareStatement(sql);
p.setString(2,registration.first_name);
p.setString(3,registration.last_name);
p.setString(4,registration.gender);
p.setString(5,registration.email_id);

As specified in the error message: "No value specified for parameter 1"
The problem here is that "first_name" is the first column in insert query for which it will expect a value.
But your PreparedStatement sets the parameter values starting from index 2. It should be done starting with index 1
That is, p.setString(1, registration.first_name)

Related

GORM query - how to use calculated field in the query and filter according to its value

Currently, I have a GORM query that calculates a counter for each table entry using a second table and returns the first table with a new field "locks_total" which doesn't exist in the original.
Now, what I want to achieve is the same table returned (with the new "locks_total" field) but filtered with "locks_total" = 0.
I can't seem to make it happen because it doesn't recognize this field in the table, what can I do to make it happen? is it possible to run the query and then execute the filter on the new result table?
This is how we currently do it-
txn := dao.postgresManager.DB().Model(&models.SecretMetadataResponse{})
txn.Table(dao.firstTableName + " as s").
Select("s.*, (SELECT COUNT(*) FROM " + dao.secondTableName + " as l where s.id = l.secret_id) locks_total ")
var secretsTotal int64
var metadataResponseEntries []models.SecretMetadataResponse
txn = txn.Count(&secretsTotal). // Saving the count before trimming according to the pagination parameters
Limit(params.Limit).
Offset(params.Offset).
Order(constants.FieldName).
Order(constants.FieldId).
Find(&metadataResponseEntries)
When the SecretMetadataResponse contains the SecretMetadata which is the same fields as in the table and the LocksTotal is the new calculated field that we want to have.
type SecretMetadataResponse struct {
SecretMetadata
LocksTotal int `json:"locks_total"`
}
Thanks in advance :)

always getting 0 for rows affected by dbexecute

I am trying to get the number of rows affected by an update query. I am using a pool connection to a SQL server database. The rows update fine, but I can't figure out how to get the number of rows affected which I want to display for the user. I have read the documentation of dbExecute and it says:
dbExecute() always returns a scalar numeric that specifies the number
of rows affected by the statement. An error is raised when issuing a
statement over a closed or invalid connection, if the syntax of the
statement is invalid, or if the statement is not a non-NA string.
I thought maybe the pool was the issue, so I also tried it with a regular dbConnect, and still got 0 for res.
Can someone show how I can pull out and display to the user the number of rows affected?
observeEvent(input$recupdate, {
res <-
#poolWithTransaction(con2, function(con2) {
dbExecute(con2, paste(
"UPDATE [Test_DB].[dbo].[mlt] SET testvar = 1 where idnum in ('",
trim(paste(filteredData()$idnum, collapse="','")),"')", sep=""))
#})
#print(res)
showModal(modalDialog(
title = "Rows affected:",
res,
easyClose = TRUE,
footer = NULL
))
})

How to read each row in a groovy-sql statement?

I am trying to read a table having five rows and columns. I have used sql.eachRow function to read eachRow and assign the value to a String. I am getting an error "Groovy:[Static type checking] - No such property: MachineName for class: java.lang.Object"
My code:
sql.eachRow('select * from [MACHINES] WHERE UpdateTime > :lastTimeRead, [lastTimeRead: Long.parseLong(lastTimeRead)])
{ row ->
def read = row.MachineName
}
but MachineName is my column name. How can i overcome this error.
Using dynamic Properties with static type checking is not possible*.
However, eachRow will pass a GroovyResultSet as first parameter to the Closure. This means that row has the type GroovyResultSet and so you can access the value using getAt
row.getAt('MachineName')
should work. In groovy you can also use the []-operator:
row['MachineName']
which is equivalent to the first solution.
*) without a type checking extension.
If you Know the Column name you can just use the Below.
"$row.MachineName"
But if you don't Know column name or having some issue, still it can be accessed using an array of Select.
sql.eachRow('select * from [MACHINES] WHERE UpdateTime > :lastTimeRead, [lastTimeRead: Long.parseLong(lastTimeRead)])
{ row->
log.info "First value = ${row[0]}, next value = ${row[1]}"
}

SQL - Change Column A value when Column B is less than a certain value

Using sql query on a DB and importing information into another DB. So, I want to change the value of a column if the date in Column B is less than a certain value.
e.g.- If Column B is less than 01/01/2015 then column A = 0, otherwise leave A alone.
I have tried a few variations my latest incarnation is which obviously doesn't work.
CASE
WHEN ColB <" + Constants.StartOfYear.ToString("yyyy-MM-dd") + #"
THEN ColA = 0
END
I use lots of other CASE statement and have already selected all my columns from the table
If I uderstand you right, all you want is update some values.
If it's your case, you can use UPDATE DML:
String sql =
#"update MyTable
set ColA = 0
where ColB < #prm_ColB"; // '#' - For MS SQL, ':' for Oracle etc.
then assign value to prm_ColB and execute it like that:
// Assuming that you're working with MS SQL
using (var con = new SqlConnection(YourConnectionString)) {
con.Connect();
using (var q = new SqlCommand(con)) {
q.CommandText = sql;
// Put actual parameter value here
q.Parameters.AddWithValue("#prm_ColB", new DateTime(DateTime.Now.Year, 1, 1));
q.ExecuteNonQuery();
}
}
give your RDBMS an actual DateTime value via binding variable (#prm_ColB) do not try converting the date into string for hardcoding.

Multiple parameter values

I have a problem with BIRT when I try to pass multiple values from report parameter.
I'm using BIRT 2.6.2 and eclipse.
I'm trying to put multiple values from cascading parameter group last parameter "JDSuser". The parameter is allowed to have multiple values and I'm using list box.
In order to be able to do that I'm writing my sql query with where-in statement where I replace text with javascript. Otherwise BIRT sql can't get multiple values from report parameter.
My sql query is
select jamacomment.createdDate, jamacomment.scopeId,
jamacomment.commentText, jamacomment.documentId,
jamacomment.highlightQuote, jamacomment.organizationId,
jamacomment.userId,
organization.id, organization.name,
userbase.id, userbase.firstName, userbase.lastName,
userbase.organization, userbase.userName,
document.id, document.name, document.description,
user_role.userId, user_role.roleId,
role.id, role.name
from jamacomment jamacomment left join
userbase on userbase.id=jamacomment.userId
left join organization on
organization.id=jamacomment.organizationId
left join document on
document.id=jamacomment.documentId
left join user_role on
user_role.userId=userbase.id
right join role on
role.id=user_role.roleId
where jamacomment.scopeId=11
and role.name in ( 'sample grupa' )
and userbase.userName in ( 'sample' )
and my javascript code for that dataset on beforeOpen state is:
if( params["JDSuser"].value[0] != "(All Users)" ){
this.queryText=this.queryText.replaceAll('sample grupa', params["JDSgroup"]);
var users = params["JDSuser"];
//var userquery = "'";
var userquery = userquery + users.join("', '");
//userquery = userquery + "'";
this.queryText=this.queryText.replaceAll('sample', userquery);
}
I tryed many different quote variations, with this one I get no error messages, but if I choose 1 value, I get no data from database, but if I choose at least 2 values, I get the last chosen value data.
If I uncomment one of those additional quote script lines, then I get syntax error like this:
The following items have errors:
Table (id = 597):
+ An exception occurred during processing. Please see the following message for details: Failed to prepare the query execution for the
data set: Organization Cannot get the result set metadata.
org.eclipse.birt.report.data.oda.jdbc.JDBCException: SQL statement does not return a ResultSet object. SQL error #1:You have an error in
your SQL syntax; check the manual that corresponds to your MySQL
server version for the right syntax to use near 'rudolfs.sviklis',
'sample' )' at line 25 ;
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to
your MySQL server version for the right syntax to use near
'rudolfs.sviklis', 'sample' )' at line 25
Also, I should tell you that i'm doing this by looking from working example. Everything is the same, the previous code resulted to the same syntax error, I changed it to this script which does the same.
The example is available here:
http://developer.actuate.com/community/forum/index.php?/files/file/593-default-value-all-with-multi-select-parsmeter/
If someone could give me at least a clue to what I should do that would be great.
You should always use the value property of a parameter, i.e.:
var users = params["JDSuser"].value;
It is not necessary to surround "userquery" with quotes because these quotes are already put in the SQL query arround 'sample'. Furthermore there is a mistake because userquery is not yet defined at line:
var userquery = userquery + users.join("', '");
This might introduce a string such "null" in your query. Therefore remove all references to userquery variable, just use this expression at the end:
this.queryText=this.queryText.replaceAll('sample', users.join("','"));
Notice i removed the blank space in the join expression. Finally once it works finely, you probably need to make your report input more robust by testing if the value is null:
if( params["JDSuser"].value!=null && params["JDSuser"].value[0] != "(All Users)" ){
//Do stuff...
}