Exception: conversion from UNKNOWN to UNKNOWN is unsupported - sql-server

I'm converting some jdbc code from MySql to SQL Server. When trying to
query = "Update ReportSetup "
+ "set N_ID=?, "
+ "R_Default=?, "
+ "R_Name=?, "
+ "R_Module=? "
+ " where R_ID = ?";
}
PreparedStatement stmt =
(PreparedStatement) con.prepareStatement(query, Statement.RETURN_GENERATED_KEYS);
stmt.setInt(1, ri.getNodeID());
stmt.setInt(2, (ri.isDefault()) ? 1 : 0);
stmt.setString(3, ri.getName());
Object o = ri.getReportModule();
stmt.setObject(4, o);
The last statement stmt.setObject(4,o) throws the exception.
ri.getReportModule returns an instance of a class which implements Externalizable.
The method writeExternal() of that class is implemented as
public final void writeExternal(final ObjectOutput objectOutput) throws IOException {
for (int i=0; i<pdV.size(); i++) {
PropertyDescriptor pd = pdV.elementAt(i);
try {
Method m = pd.getReadMethod();
Object val = pd.getReadMethod().invoke(this);
System.out.print("writing property " + i + ": " + pd.getName() + " = " + val);
objectOutput.writeObject(val);
} catch (Exception e) {
e.printStackTrace();
}
}
}
The database column in question is defined as
varbinary(max), not null
The code works well using MySql but I can't figure out what to do to make it run with Sql Server.
Any suggestions would be very much appreciated

The problem was that sql server is not happy to save a serialization (as done when implementing externalizable). .setObject() fails. The solution is to use setBinaryStream().
// Sql Server can't do an stmt.setObject(4,o) "Conversion from UNKNOWN to UNKNOWN not supported"
// Serialize the object to an output stream and then read it in again into the stmt.
Object o = ri.getReportModule();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream objectOutput = new ObjectOutputStream(bos);
objectOutput.writeObject(o);
objectOutput.flush();
InputStream objectInput = new ByteArrayInputStream(bos.toByteArray());
stmt.setBinaryStream(4, objectInput);
Cheers
Christian

Related

Kotlin: sqlite database table not creating

Iam new to Kotlin. I am developing a "personality guessing" app. it was working fine but when i added SQLite database when I run it keeps crashing when i reach to activity on which SQLite is integrated. my table does not create.
error log image here in link
Error log:
2020-06-04 13:18:10.757 16744-16744/? E/example.guessm: Unknown bits set in runtime_flags: 0x8000
2020-06-04 13:18:12.088 16744-16776/com.example.guessme E/eglCodecCommon: glUtilsParamSize: unknow param 0x000082da
2020-06-04 13:18:12.088 16744-16776/com.example.guessme E/eglCodecCommon: glUtilsParamSize: unknow param 0x000082da
2020-06-04 13:18:33.961 16744-16744/com.example.guessme E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.guessme, PID: 16744
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.guessme/com.example.guessme.QuizActivity}: java.lang.IllegalStateException: getDatabase called recursively
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3270)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3409)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2016)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7356)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)
Caused by: java.lang.IllegalStateException: getDatabase called recursively
at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:357)
at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:317)
at com.example.guessme.DbHelper.addQuestion(DbHelper.kt:80)
at com.example.guessme.DbHelper.addQuestions(DbHelper.kt:45)
at com.example.guessme.DbHelper.onCreate(DbHelper.kt:35)
at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:412)
at android.database.sqlite.SQLiteOpenHelper.getReadableDatabase(SQLiteOpenHelper.java:341)
at com.example.guessme.DbHelper.getAllQuestions(DbHelper.kt:93)
at com.example.guessme.QuizActivity.onCreate(QuizActivity.kt:29)
at android.app.Activity.performCreate(Activity.java:7802)
at android.app.Activity.performCreate(Activity.java:7791)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1299)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3245)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3409) 
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83) 
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135) 
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2016) 
at android.os.Handler.dispatchMessage(Handler.java:107) 
at android.os.Looper.loop(Looper.java:214) 
at android.app.ActivityThread.main(ActivityThread.java:7356) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930) 
Code snippet of onCreate method in DbHelper class:
private val DATABASE_VERSION = 2
// Database Name
private val DATABASE_NAME = "PersonalityQuiz.db"
// tasks table name
lateinit var dbase: SQLiteDatabase
class DbHelper (context: Context) : SQLiteOpenHelper(context, DATABASE_NAME, null, DATABASE_VERSION) {
override fun onCreate(db: SQLiteDatabase) {
dbase = db
val sql = ("CREATE TABLE IF NOT EXISTS " + TABLE_QUEST + " ( "
+ KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + KEY_QUES
+ " TEXT, " + KEY_OPTA + " TEXT, "
+ KEY_OPTB + " TEXT, " + KEY_OPTC + " TEXT)")
db.execSQL(sql)
addQuestions()
db.close()
}
code snippet of addQuestions function where i insert questions to database:
// Adding new question
fun addQuestion(quest: Question) {
dbase = this.writableDatabase
val values = ContentValues()
values.put(KEY_QUES, quest.getQUESTION())
values.put(KEY_OPTA, quest.getOPTA())
values.put(KEY_OPTB, quest.getOPTB())
values.put(KEY_OPTC, quest.getOPTC())
// Inserting Row
dbase.insert(TABLE_QUEST, null, values)
}
code snipppet for onUpgrade method:
override fun onUpgrade(db: SQLiteDatabase, oldV: Int, newV: Int) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS $TABLE_QUEST")
// Create tables again
onCreate(db)
}
You cannot access writableDatabase within onCreate().
Either remove the addQuestions() call from onCreate(), or pass the SQLiteDatabase from onCreate() as a parameter to addQuestions().

Alway get an error "No attribute named 'name' is defined" if try to process multiple lines from csv data feed

In my test script I try to process 100 lines data from csv data feed via following statement:
private val scn = scenario("test_scn").feed(insertFeeder, 100).exec(httpReq)
But I always get an error:
[ERROR] HttpRequestAction - 'httpRequest-1' failed to execute: No attribute named 'name' is defined
Could you please help me to find out the root cause? thank you.
Here is the script:
private val insertFeeder = csv("test_data.csv").queue
private val csvHeader = GeneralUtil.readFirstLine(""test_data.csv"")
private val httpConf = http .baseURL("http://serviceURL") .disableFollowRedirect .disableWarmUp .shareConnections
private var httpReq = http("insert_request") .post("/insert")
for (i <- 0 to 99) {
val paramsInArray = csvHeader.split(",")
for (param <- paramsInArray) {
if (param.equalsIgnoreCase("name")) {
httpReq = httpReq.formParam(("name" + "[" + i +"]").el[String] , "${name}")
}
if (param.equalsIgnoreCase("url")) {
httpReq = httpReq.formParam(("url" + "[" + i +"]").el[String] , "${url}")
}
if (!param.equalsIgnoreCase("name") && !param.equalsIgnoreCase("url")) {
val firstArg = param + "[" + i + "]"
val secondArg = "${" + param + "}"
httpReq = httpReq.formParam(firstArg, secondArg)
}
}
}
private val scn = scenario("test_scn") .feed(insertFeeder, 100) .exec(httpReq)
setUp( scn.inject( constantUsersPerSec(1) during (1200 seconds) ).protocols(httpConf) ).assertions(global.failedRequests.count.lte(5))
And the data in test_data.csv is:
name,url,price,size,gender
image_1,http://image_1_url,100,xl,male
image_2,http://image_2_url,90,m,female
image_3,http://image_3_url,10,s,female
...
image_2000,http://image_2000_url,200,xl,male
By the way, if I process only 1 line, it works well.
Read the document again, and fixed the issue. If feed multiple records all at once, the attribute names will be suffixed from 1.
https://gatling.io/docs/current/session/feeder/#csv-feeders

Sqlite database insert returns always -1 on some devices

I try to insert an entry in sqlite db, but this does not work on some devices!
The insertion works with the device Huawei Nexus 6P (Android 6.0, API23) very well, but not with the device Samsung SM-G930F (Android 6.0.1, API23).
Can you please help me! The return code is always "res = -1".
Here is my code for inserting a new registration:
public boolean insertRegistration(Registration registration) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put("phoneNumber", registration.getPhoneNumber());
cv.put("serverPassword", registration.getServerPassword());
cv.put("chatPassword", registration.getChatPassword());
cv.put("username", registration.getUsername());
cv.put("fileURL", registration.getFileURL());
long res = 0;
try
{
res = db.insert(TABLE_USER, null, cv);
}
catch(SQLException e)
{
// Sep 12, 2013 6:50:17 AM
Log.e("Exception", "SQLException" + String.valueOf(e.getMessage()));
e.printStackTrace();
}
if(res == -1)
throw new RuntimeException("New registration can not be inserted into local db");
db.close();
return res >= 0;
}
The debugger will also not come to the catch! No warning or errors will be returned!
And the db looks like this:
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(DATABASE_CREATE_USER);
}
Create user db string:
private static final String DATABASE_CREATE_USER = "create table "
+ TABLE_USER + "("
+ "id integer primary key autoincrement, "
+ "phoneNumber text not null, "
+ "serverPassword text not null, "
+ "chatPassword text not null, "
+ "fileURL text not null, "
+ "username text not null"
+ ");";
I always get the return code "-1", if I debug this line "res = db.insert(TABLE_USER, null, cv);" on the device "Samsung SM-G930F".
Thank you in Advance!

Dapper Contrib Insert MySQL Syntax Error

Hey I am getting syntax error in MySQL using Dapper.Contrib
MySQL server version for the right syntax to use near '[cause_code],[cause_name]) values ('000-DDH', 'No Money')' at line 1
the correct syntax for Insert in mysql is
"Insert Into `tbl_cause` (`cause_code`, `cause_name`) VALUES('blah', 'blah')";
my code:
var entity = new Cause { cause_code = "000-DDH", cause_name = "No Money" };
using (IDbConnection cn = ConStr.Conn())
{
long ins = cn.Insert(entity);
if (ins > 0)
{
MessageBox.Show("Cause Code: " + entity.cause_code + " Successfully Added!");
GDRD();
}
else {
MessageBox.Show("Cause Code: " + entity.cause_code + " While trying to Add an Error Occurred!");
}
}
how to solve this? thanks in Advance
It's you again :)
Does the class Cause have a Table("tbl_cause") directive?
Read the dapper contrib extensions documentation here

How to know which server is online or offline in a OAM cluster

Hello I´ve a problem when I try to monitor which one of a cluster oam servers is online and offline I use the the getServerDiagnosticInfo() method of AccessClient class from aSDK, but the Hashtable that returns only contains Keys (name and port of server) and Values that contains another HashTable (ObKeyMapVal a subtype of HashTable) but I think that this object must contains the health, server port, server name and number of connections as mentioned in the API doc but when I print the size and contents of it only prints "0" and [] (its empty)
snippet:
try{
AccessClient ac = AccessClient.createDefaultInstance("/dir",AccessClient.CompatibilityMode.OAM_10G);
Hashtable info = ac.getServerDiagnosticInfo();
Set<?> servers = info.keySet();
Collection<?> serverInfo = info.values();
System.out.println("Num of servers: " + servers.size());
Iterator it = servers.iterator();
Object servidor = null;
Object dato = null;
while(it.hasNext()){
servidor = it.next();
System.out.println("Server: " + servidor);
dato = info.get(servidor);
System.out.println("Data: " + dato);
ObKeyValMap ob = (ObKeyValMap) dato;
System.out.println("Size: " + ob.keySet().size());
System.out.println("Is Empty: " + ob.keySet().isEmpty());
System.out.println("Properties: " + ob.keySet());
}
ac.shutdown();
} catch (oracle.security.am.asdk.AccessException e) {
e.printStackTrace();
} catch (Exception e){
e.printStackTrace();
}
And got the next output:
Num of servers: 2
Server: myserver1.com5575
Data: {}
Size: 0
Is Empty: true
Properties: []
Server: myserver2.com5575
Data: {}
Size: 0
Is Empty: true
Properties: []
Thanks for your help !!!
Once you get the OAM Server Host and Port using getServerDiagnosticInfo(). Try to do telnet ( I am not Java Expert, following link may help How to connect/telnet to SPOP3 server using java (Sockets)?) , if the server is up the telnet session will be established.

Resources