Exception is The column index is out of range: 16, number of columns: 15.; nested exception is org.postgresql.util.PSQLException: The column index is out of range: 16, number of columns: 15. while submitting the form using this query. Kindly suggest. Your help will be appreciable.
#Override
public int insertNewApplication(TokenApplicantDetails tpd)
{
String sql = "INSERT INTO token_applicant_details"
+ "(application_no,applicant_name, applsex, "
+ "designation, date_of_superannuation, "
+ "phone_no, mobile_no, "
+ "office_type_code,ou_code,token_manufacturer_code,token_user_id,token_password, "
+"certificate_no,certificate_issue_date,certificate_expiry_date, "
+"fixed_ip_address,ref_no,form_type,original_application_receiving_date, "
+"scanned_application_receiving_date,residential_address,staff_status, "
+"email_id, enrollment_no, dispatch_no,fixed_ip_active, "
+"refId,Deacivated_on) VALUES (null,?, ?, ?,to_date(?,'DD/MM/YYYY'), ?, ?, ?, ?, ?, ?, ?,null,null,null,null,null,?,null,null,?,?,?,null,null,null,null,null)";
System.out.println("not inserted");
return jdbcTemplate.update(sql,new Object[]{tpd.getApplication_no(),tpd.getApplicant_name(), tpd.getApplsex(),tpd.getDesignation(),tpd.getDate_of_superannuation(),tpd.getPhone_no(),tpd.getMobile_no(),
tpd.getOffice_type_code(),tpd.getOu_code(),tpd.getToken_manufacturer_code(),tpd.getToken_user_id(),tpd.getToken_password(),tpd.getCertificate_no(),tpd.getCertificate_issue_date(),tpd.getCertificate_expiry_date(),
tpd.getFixed_ip_address(),tpd.getRef_no(),tpd.getForm_type(),tpd.getOriginal_application_recieving_date(),
tpd.getScanned_application_recieving_date(),tpd.getResidential_address(),tpd.getStaff_status(),
tpd.getEmail_id(),tpd.getEnrollment_no(),tpd.getDispatch_no(),tpd.getFixed_ip_address(),tpd.getRefId(),tpd.getDeactivated_on(),});
}
Your database table has 15 columns, whereas you are attempting to insert 16 values into the row. If I were you I'd tidy up the formatting of your query (e.g. one value per line) so that you can see better which value is mismatched.
Better would be to use NamedParameterJdbcTemplate instead; this allows you to match up column values explicitly.
Related
Using odbctest and Snowflake 64-bit ODBC driver for Windows:
Created a table in snowflake using this DDL:
CREATE TABLE "SFDEST"."QAUSER"."BT14726"
("VARCHAR_10_COL" VARCHAR (10),
"VARCHAR_4000_COL" VARCHAR (4000) ,
"CHAR_10_COL" CHAR (10) ,
"CLOB_COL" VARIANT,
"ROWID" CHAR (18) NOT NULL )
Then attempted to prepare an insert statement:
SQL attempted:
INSERT INTO "SFDEST"."QAUSER"."BT14726"
("VARCHAR_10_COL",
"VARCHAR_4000_COL",
"CHAR_10_COL",
"ROWID",
"CLOB_COL")
VALUES ( ?, ?, ?, ?, ?)
But this error was returned:
Prepare of destination insert statement failed. SQL compilation error:
Expression type does not match column data type, expecting VARIANT but
got VARCHAR(1) for column CLOB_COL
This is the relevant portion of odbc trace:
sqdrsvc 3dfc-52bc ENTER SQLPrepare
HSTMT 0x000000435C961620
UCHAR * 0x000000435D262720 [ 140] "INSERT INTO "SFDEST"."QAUSER"."BT14726" ("VARCHAR_10_COL",
"VARCHAR_4000_COL", "CHAR_10_COL", "ROWID", "CLOB_COL") VALUES ( ?,
?, ?, ?, ?) "
SDWORD 140
sqdrsvc 3dfc-52bc EXIT SQLPrepare with return code
-1 (SQL_ERROR)
HSTMT 0x000000435C961620
UCHAR * 0x000000435D262720 [ 140] "INSERT INTO "SFDEST"."QAUSER"."BT14726" ("VARCHAR_10_COL",
"VARCHAR_4000_COL", "CHAR_10_COL", "ROWID", "CLOB_COL") VALUES ( ?,
?, ?, ?, ?) "
SDWORD 140
DIAG [22000] SQL compilation error: Expression type does not match column data type, expecting VARIANT but got
VARCHAR(1) for column CLOB_COL (2023)
If you have a string that is formatted as a valid JSON blob, you need to use PARSE_JSON to convert it into an actual variant type so that SnowFlake can recognize it as such.
Probably something like this:
INSERT INTO "SFDEST"."QAUSER"."BT14726"
("VARCHAR_10_COL",
"VARCHAR_4000_COL",
"CHAR_10_COL",
"ROWID",
"CLOB_COL")
VALUES ( ?, ?, ?, ?, PARSE_JSON(?))
Having a blank table with three columns
CREATE TABLE AssyData ( AID int NOT NULL PRIMARY KEY UNIQUE , MaxDef float , MaxDefLC int , MaxDefNID int , Comps text , SubAssys text )
I would like to Update or insert new values if the new MaxMag is larger than the current one and if the AID is the same. AID is a unique Primary key. Assuming an AID of 100 I have tried the following, but with no success:
INSERT INTO AssyData
(AID , MaxDef , MaxDefLC , MaxDefNID , Comps , SubAssys)
VALUES( 100 , 101 , 202 , 203 , "" , "")
ON CONFLICT(AID)
DO UPDATE
SET
MaxDef = excluded.MaxDef ,
MaxDefNID = excluded.MaxDefNID ,
MaxDefLC = excluded.MaxDefLC ,
Comps = excluded.Comps ,
SubAssys = excluded.SubAssys
WHERE excluded.MaxDef > 100
I get the error "near "ON": syntax error"
What is wrong with my statement?
Thanks Shawn for the Approach.
In case your vesrsion of SQLite does not allow the use of UPSERT you can achieve what you need in 2 steps:
INSERT OR IGNORE INTO AssyData
(AID, MaxDef, MaxDefLC, MaxDefNID, Comps, SubAssys)
VALUES(100, 111, 202, 203, '', '');
This INSERT OR IGNORE will fail without an error if you try to insert a row with an AID that already exists in the table.
Then:
UPDATE AssyData
SET
MaxDef = 111,
MaxDefLC = 202,
MaxDefNID = 203,
Comps = '',
SubAssys = ''
WHERE AID = 100 AND MaxDef < 111;
This will fail if the row to be updated contains MaxDef equal or greater than the value 111.
See the demo.
In general such code needs special care when implemented, because as you can see the value of MaxDef (111 in this example) must be set 3 times.
Assuming you're using a somewhat recent (3.24 or newer) version of sqlite, you can use what's known as UPSERT:
INSERT INTO AssyData(AID, MaxMag, MaxDefNID) VALUES (?, ?, ?)
ON CONFLICT(AID) DO UPDATE SET MaxMag = excluded.MaxMag
, MaxDefNID = excluded.MaxDefNID
WHERE excluded.MaxMag > MaxMag;
I am using the RODBCext package and the RODBC package to execute a stored procedure in SQL server 2008 using R. If I use this code the stored procedure works.
query <- "EXEC [dbo].[usp_SchoolMerge] #Number = ?,
#Name = ?,
#Type = ?,
#Comments = ?,
#DualEnrollment =?,
#CEP = ?,
#DistrictGuidId = ?,
#ImportName = ?,
#ImportID = ?"
query <- gsub("[[:space:]]+", " ", query)
con2 <- odbcConnect("database", uid="userid", pwd="password")
for(i in 1:nrow(us11_12_00_school)) {
sqlExecute(con2, query, us11_12_00_school[i,])
}
odbcClose(con2)
If I try to use the vectorized form explained here under 2.3.2 Using parameterized queries.
query <- "EXEC [dbo].[usp_SchoolMerge] #Number = ?,
#Name = ?,
#Type = ?,
#Comments = ?,
#DualEnrollment =?,
#CEP = ?,
#DistrictGuidId = ?,
#ImportName = ?,
#ImportID = ?"
query <- gsub("[[:space:]]+", " ", query)
con2 <- odbcConnect("database", uid="userid", pwd="password")
sqlExecute(con2, query, us11_12_00_school)
odbcClose(con2)
I get this error in R.
Error in sqlExecute(con2, query, us11_12_00_school) :
24000 0 [Microsoft][ODBC SQL Server Driver]Invalid cursor state
[RODBCext] Error: SQLExecute failed
If I use a data frame with only one row the vectorized code works. Anyone else had this problem? Any ideas?
Seems like you want to use only the first column of the us11_12_00_school - which you pass in the loop-version of the function with us11_12_00_school[i,]. In the vectorised version though, you pass in the whole dataframe!
I havent tested it out, but i guess passing the dataframe as us11_12_00_school[1,] in the vectorised version would give you the expected results?
I use the code below, and seems to work well. Hopefully it helps you too.
require(RODBC)
require(RODBCext)
ExecuteQuery <- function(query, arguments){
dbhandle <- odbcDriverConnect('driver={SQL Server Native Client 11.0};server=SereverName;database=DbName;trusted_connection=yes')
if(missing(arguments))
result <- sqlExecute(dbhandle, query = query, fetch = TRUE)
else
result <- sqlExecute(dbhandle, query =query, data=arguments, TRUE)
close(dbhandle)
return(result)
}
CallProcWithSomeParams <- function(param1, param2){
ExecuteQuery('exec dbo.procName ?, ?', data.frame(param1, param2))
}
I am not familiar with SQL that much. I'm trying to insert multiple rows of data into a table that if there exist a row with with duplicate value in BusinessFilterPhrase column then just don't insert. I wrote a pseudocode of what I think it should be.
if (filterCategoryList != null)
{
foreach (KeyValuePair<string, int> filter in filterCategoryList)
{
cmd.CommandText = "insert into tblBusinessName (BusinessFilterPhrase,BusinessCategoryID)" +
"select #BusinessFilterPhrase,#BusinessCategoryID" +
"from tblBusinessName as t1" +
"where NOT EXISTS" +
"( select * from tblBusinessName as d1 where d1.BusinessFilterPhrase = #BusinessFilterPhrase) ";
cmd.Parameters.AddWithValue("#BusinessFilterPhrase", filter.Key);
cmd.Parameters.AddWithValue("#BusinessCategoryID", filter.Value.ToString());
cmd.ExecuteNonQuery();
}
}
You code looks correct. I would write it as:
insert into tblBusinessName(BusinessFilterPhrase, BusinessCategoryID)
select #BusinessFilterPhrase, #BusinessCategoryID
from tblBusinessName t1
where NOT EXISTS (select 1
from tblBusinessName d1
where d1.BusinessFilterPhrase = #BusinessFilterPhrase
)
(The changes are only cosmetic.)
EDIT:
If performance is an issue, create an index on BusinessFilterPhrase:
create index idx_tblBusinessName_BusinessFilterPhrase on tblBusinessName(BusinessFilterPhrase);
You can make this a unique index, if you want the database to enforce the uniqueness of the column (it will generate an error when duplicate values would be inserted).
I'm working on a program that is able to make quizzes by exporting questions into a database. I've looked on the internet for a bit and it said that one of the easiest ways to import or export to a database in python is to use the SQLite3 plugin, so I'm trying it out.This is the first time I've used the SQLite3 plugin with python, and I keep getting a syntax error on the self.connection.commit() in:
def AddQuestion(self, Question, Answer1, Answer2, Answer3, Answer4):
self.cursor.execute("""INSERT INTO questions
VALUES (?, ?, ?, ?, ?, ?)""", (None, Question, Answer1, Answer2, Answer3, Answer4, CorrectAnswer)
self.connection.commit()
If I were to turn it into a comment by adding # before it, it would tell me that the print in this was a syntax error:
print ("Would you like to make a test? Or would you like to take a test?")
Maybe its my indentation, or am I doing something wrong?
import squlite3
class QuestionStorage(object):
def _init_(self, path):
self.connection = sqlite3.connect(path)
self.cursor = self.connection.cursor ()
def Close(self):
self.cursor.close()
self.connection.close()
def CreateDb(self):
query = """CREATE TABLE questions
(id INTEGER PRIMARY KEY, Question TEXT, Answer1 TEXT, Answer2 TEXT, Answer3 TEXT, Answer4 TEXT, CorrectAnswer TEXT)"""
self.cursor.exeute(query)
self.connection.commit()
#self.cursor.close()
def AddQuestion(self, Question, Answer1, Answer2, Answer3, Answer4):
self.cursor.execute("""INSERT INTO questions
VALUES (?, ?, ?, ?, ?, ?)""", (None, Question, Answer1, Answer2, Answer3, Answer4, CorrectAnswer)
self.connection.commit()
def GetQuestion(self, index = None):
self.cursor.execute("""SELECT * FROM questions WEHRE id=?""", (index,))
print ("Would you like to make a test? Or would you like to take a test?")
testTaker = input ("To create a test, type Create. To take a test, type Take.")
if testTaker == "Create":
testName = input ("Give your test a name.")
testQ = int(input ("How many questions will be on this test? (Numeric value only.)"))
testType = input ("Will this test be multiple choice? (y/n)")
if testType == "N" or "n":
counter = 1
qs = QuestionStorage("questions.db")
qs.CreateDb()
counter = 1
while counter >= testQ:
Answer = []
Question = input ("What is your question?")
Answer[1] = input ("What is the first answer?")
Answer[2] = input ("What is the second answer?")
Answer[3] = input ("What is the third answer?")
Answer[4] = input ("What is your last answer?")
correctAnswer = input("Which answer is the correct answer? (1, 2, 3, or 4?)")
Answer[5] = Answer[correctAnswer]
qs.AddQuestion(Question, Answer[1] , Answer[2], Answer[3], Answer[4], Answer[5])
counter +=1
else:
and then after the else, I'd have the code for reading the database to take a test.
If anyone can help me out with this, that would be great. Right now I'm just trying to get it to the point where I can run it in debug.
You forgot to close the parentheses here:
self.cursor.execute("""INSERT INTO questions
VALUES (?, ?, ?, ?, ?, ?)""", (None, Question, Answer1, Answer2, Answer3, Answer4, CorrectAnswer)
Put another closing ) at the end of the line.