When calling a DB function in Postgres, the type for String changes to text and that of DateTime to timestamp. Is there any way to ensure this doesn't happen?
Setup:
a DB function:
foo(v_from character varying, v_to character varying, v_date date)
Dapper code:
public static decimal GetValue(DateTime vdate, string cur) {
string sql = #"SELECT _public.foo(#vFrom, #vTo, #vDate)";
var data = connection.QueryFirstOrDefault<decimal>(
sql,
new
{
vFrom = cur,
vTo = cur,
vDate = valdate,
}
);
}
I receive the following error:
Npgsql.PostgresException : 42883: Function _public.foo(text, text, timestamp without time zone) does not exist
Somehow string is converted to text instead of character varchar. Similar story for DateTime to timestamp.
Tried the variation with DynamicParameters.Add(), but still the same result.
Try this?
public static decimal GetValue(DateTime vdate, string cur) {
string sql = #"SELECT _public.foo(#vFrom::character varying, #vTo::character varying, #vDate::date)";
var data = connection.QueryFirstOrDefault<decimal>(
sql,
new
{
vFrom = cur,
vTo = cur,
vDate = valdate,
}
);
}
Related
I'm having problem with foreign key while adding a new habit and inserting it's data in db and I don't really know why, because everything seems right. the error is:
[ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception: DatabaseException(FOREIGN KEY constraint failed (code 787)) sql 'INSERT OR FAIL INTO Habits (userId, text, emoji, period, startPeriod) VALUES (?, ?, ?, ?, NULL)' args [1, habit, ☺, [1,2,3,4,5,6,7]]
error accrued here:
class DataService {...
late final Database db;
Future<void> addHabit(Habit newHabit) async {
final newHabitId = await HabitsDb.createHabit(db, newHabit);//error accrued here
final days = (await HabitsDb.getAllDays(db)).map((e) => Day.fromDb(e, []));
for (final day in days) {
if (newHabit.startPeriod != null &&
newHabit.startPeriod!.compareTo(day.date) > 0) {
continue;
}
if (newHabit.period.contains(day.date.weekday)) {
await HabitsDb.createHabitDay(
db, day.date.millisecondsSinceEpoch, newHabitId);
}
}
await _reloadDaysInCache();
_loadHabits();
} ...}
then:
class HabitsDb{...
static Future<int> createHabit(Database db, Habit habit) async {
return db.insert(HabitsTable.tableName, await habit.toDb(),
conflictAlgorithm: ConflictAlgorithm.fail);
}...}
model:
class Habit {
late final int id;
late final int userId;
late String text;
late String emoji;
late final List<int> period;
late final DateTime? startPeriod;
...
Future<Map<String, dynamic>> toDb() async {
print(text);
print(userId);
return {
//HabitsTable.id: id,
HabitsTable.userId: userId,
HabitsTable.text: text,
HabitsTable.emoji: emoji,
HabitsTable.period: jsonEncode(period),
HabitsTable.startPeriod: startPeriod?.millisecondsSinceEpoch
};
}...}
creating table:
class HabitsTable {
static const String tableName = 'Habits';
static const String id = 'id';
static const String userId = 'userId';
static const String text = 'text';
static const String emoji = 'emoji';
static const String period = 'period';
static const String startPeriod = 'startPeriod';
static const String createQuery = '''
CREATE TABLE IF NOT EXISTS $tableName (
$id INTEGER PRIMARY KEY AUTOINCREMENT,
$userId INTEGER NOT NULL,
$text TEXT NOT NULL,
$emoji TEXT NOT NULL,
$period TEXT NOT NULL,
$startPeriod INTEGER,
FOREIGN KEY($userId) REFERENCES ${UsersTable.tableName}(id));''';
}
if more code is needed you can check https://github.com/sarasoltan/habit_tracker
plz help if you know how to solve this error.
contract KYCCHECK{
function KYCCHECK(){}
struct User{
uint id;
bool isVerified;
string fname;
string mname;
string lname;
string genderValue;
string maritalStat;
string stat;
string identity;
}
mapping(uint => User) kyclist;
function setKYCData(uint uid,string firstname,string middlename,string lastname,string gvalue,string maritalVal,string statusVal,string identityVal) {
kyclist[uid].fname = firstname;
kyclist[uid].mname = middlename;
kyclist[uid].lname = lastname;
kyclist[uid].genderValue = gvalue;
kyclist[uid].maritalStat = maritalVal;
kyclist[uid].stat = statusVal;
kyclist[uid].identity = identityVal;
}
function getFirstName(uint uid) constant returns (string retFNameVal) {
retFNameVal = kyclist[uid].fname;
return retFNameVal;
}
function getMiddleName(uint uid) constant returns (string retMNameVal) {
retMNameVal = kyclist[uid].mname;
return retMNameVal;
}
function getLastName(uint uid) constant returns (string retLNameVal) {
retLNameVal = kyclist[uid].lname;
return retLNameVal;
}
function getGender(uint uid) constant returns(string retGenderVal) {
retGenderVal = kyclist[uid].genderValue;
return retGenderVal;
}
function getMaritalStatus(uint uid) constant returns(string retMaritalVal){
retMaritalVal= kyclist[uid].maritalStat;
return retMaritalVal;
}
function getStatus(uint uid) constant returns(string retStatus){
retStatus = kyclist[uid].stat;
return retStatus;
}
function getIdentity(uint uid)constant returns(string retIdentity){
retIdentity = kyclist[uid].identity;
return retIdentity;
}
}
Hello everyone,
This the contract i am trying to implement.
I have a form(using bootstrap with form defined "") and i need to set and get the data through form.
Problem is when i pass more than 3 arguments in setKYCData function (in above contracts)and execute get function, the value isn't displayed.
but when set is modified to take 3 arguments and get function is called with 3 arguments it works fine.
please ask if you need any more details, if anybody can share a code to create a form using solidity, web3 that'll be appreciable.
thanks in adv
A frequently asked question (also for me) was: How to convert a simple String from e.g. a JTextField to a java.sql.date Date - to insert some GUI-User-Input as correctly formatted Date into a table through a Prepared Statement.
I'd write a new convert-specified Class, which has this option.
import java.text.SimpleDateFormat;
import java.util.Date;
public class convertText {
public java.sql.Date formatStringToSQLDate(String strDate) throws Exception{
Date utilDate = new Date(); //DateFormat
SimpleDateFormat dfFormat = new SimpleDateFormat("dd.MM.yyyy"); // parse string into a DATE format
utilDate = dfFormat.parse(strDate); // convert a util.Date to milliseconds via its getTime() method
long time = utilDate.getTime(); // get the long value of java.sql.Date
java.sql.Date sqlDate = new java.sql.Date(time);
return sqlDate;
}
}
Afterwards, to use it like this.
Connection dp = DriverManager.getConnection("jdbc:ucanaccess://" + Filepath + Filename);
Statement stat = dp.createStatement();
String sql = "INSERT INTO user_table (Name, Birth) VALUES(?, ?)"; //statement as string
PreparedStatement pstmt = dp.prepareStatement(sql);
pstmt.setString(1, textFieldVorname.getText()); //replaces the first '?'
pstmt.setDate(2, Date.formatStringToSQLDate(textFieldGeburtsdatum.getText())); //replaces the second '?'
pstmt.executeUpdate(); //executes the insert-query
I have a text view in which user enters a string. I need to search for that string in a table and return a boolean value if a string matches.
I am not into SQL, so can anyone please help me figure out how to do it.
Assuming that you know the basics & the object db of type SQLiteDatabase exists in your DataAccessLayer, below is the function which returns true false based on whether the location exists or not?
public boolean IsRecordExists(long empid) throws SQLException
{
String where = "empid =" + empid;
Cursor mCursor = db.query(true, "employeeinfo", new String[] {"empid"}, where, null,null, null, null, null);
if (mCursor != null)
{
if(mCursor.moveToFirst())
return true;
else
return false;
}
return false;
}
Hi guys I want to get the summation of column values from my sqlite database in android.
and am trying to use this to get me the sum of column KEY_COST.
public Cursor fetchAllCost() {
return mDb.query(
DATABASE_TABLE,
new String[] { "SUM(KEY_COST)"},
null,
null,
null,
null,
null);
}
but its giving me a cursor and I do not know how to get the value from the Cursor object. Any one help!!!
You can return scalar values like so:
public int getColumnData() {
mDb = mDbManager.getReadableDatabase();
final SQLiteStatement stmt = mDb
.compileStatement("SELECT SUM(KEY_COST) FROM...");
// Cast as appropriate
return (int) stmt.simpleQueryForLong();
}
Or alternatively, depending on the data type use simpleQueryForString().
You should just move to the first result in the cursor with cursor.moveFirst() and then you can do cursor.getInt(1) to get the scalar value.
rawQuery
Sum value is on first column - cursor.getInt(0);
Cursor cursor = database.rawQuery(
"SELECT SUM(" + COL_NAME + ") FROM " + TABLE_NAME, null);
if(cursor.moveToFirst()) {
return cursor.getInt(0);
}
query
String[] columns = new String[] {
"sum(" + DbHelper.C_COUNT_OF_WORDS + ")"
};
String where = null;
String whereArgs[] = null;
String groupBy = null;
String having = null;
String order = null;
String limit = null;
database = dbHelper.getReadableDatabase();
Cursor cursor = database.query(DbHelper.TABLE_STATISTICS, columns, where, whereArgs, groupBy, having, order, limit);
if(cursor.moveToFirst()) {
return cursor.getInt(0);
}