Unable to search through encrypted value from sqlite database - sqlite

I am trying to find a recored with an encrypted string like
description = "oYAFfrNS2OszASY7Vo182A=="
and it is stored in sqlite database like
oYAFfrNS2OszASY7Vo182A==
in the description field.
My android code is:
Cursor c = db.query(table, columns,
whereclause,
null,
null,
null,
null);
try {
if (c.getCount() == 0) {
c.close();
return "";
}
c.moveToFirst();
int namecol = c.getColumnIndex(columns[0]);
li = (c.getString(namecol));
c.close();
} catch (Exception e) {
System.out.println("Exception: " + e.toString());
}
where table name, where clause and columns all are correct for sure but I am unable to get the result with encrypted string which I have mentioned.

I found the problem by debugging further actually there is one new line character in my encrypted string which were not passed in this.

Related

Mono SQLite: System.InvalidCastException: Specified cast is not valid

i am trying to insert this command in a dynamic way in a unity project:
public static string insertPlayerCmd = "INSERT INTO Player (Name) VALUES (?);";
I am using this method on a repository to insert a name into the database:
public AccountContents SaveAccount(string newName)
{
string name = newName;
var transaction = Finder.DB.DatabaseConnection.BeginTransaction();
var command = Finder.DB.DatabaseConnection.CreateCommand();
AccountContents newAccountContents = null;
try
{
command.CommandText = ConstantDbRequests.insertPlayerCmd;
command.Parameters.Add(newName);
var newAccount = command.ExecuteReader();
transaction.Commit();
newAccountContents = new AccountContents(newAccount.GetInt32(0), newAccount.GetString(1));
}
catch (Exception e)
{
Debug.Log(e.ToString());
}
return newAccountContents;
}
the line command.Parameters.Add(newName); throws an invalid cast exception.
I verified my database in SQLite, and the column to insert is of Text type, all the names on the SQL command are writen correctly, but i can't add the parameter to replace the ? wildcard

Cannot insert explicit value for identity column in table 'table' when IDENTITY_INSERT is set to OFF but can insert manually on db

Hi i am experiencing this error.
Cannot insert explicit value for identity column in table 'table' when IDENTITY_INSERT is set to OFF
i have checked my db structure and can insert manually in the db. my code is
public bool Save(SaveTeamAssignedVm data)
{
try
{
var newdata = _unitOfWork.TeamAssignedRepository.Add(new TeamAssigned()
{
CreatedBy = data.CreatedBy,
DateCreated = DateTime.Now,
UpdatedBy = "",
DateUpdated = DateTime.Now,
IsActive = true
});
return true;
}
catch (Exception ex)
{
throw ex;
}
I have not been inserting any sort of data that will interrupt the identity column.
i even removed other data to check if other data is the error but no matter what i it still has the error. any idea on why?

UWP SQLite - Return null but data in table

I have datain my database (shown in the screen)
But the returned values are null? How is that possible, in the output I got this:
This is the code I'm using:
public static SQLiteConnection dbConnection = new SQLiteConnection("RPR_REKENSOFTWARE_DB.db");
public static List<String> GetParts()
{
var items = new List<String>();
try
{
string sSQL = #"SELECT * FROM parts;";
ISQLiteStatement dbState = dbConnection.Prepare(sSQL);
// Get the records
while (dbState.Step() == SQLiteResult.ROW)
{
// Say what it is.
string partNr = dbState[1] as string;
items.Add(partNr);
}
return items;
}
catch (Exception ex)
{
Debug.WriteLine(ex);
throw ex;
}
}
This is the database I'm using:
The reason is that you are converting the value from database to string, although it is actually an int. You should do:
string partNr = ( ( int )dbState[ 1 ] ).ToString();
Or more simply:
string partNr = dbState[ 1 ].ToString();
The reason is that the row returned from database is contains .NET equivalents of the DB column types and hence dbState[1] is an int. When you use as string on an int however, it cannot be cast and you get null.

How to get out integer from database using IDataReader and Mapper

I'm very new in programming and this is my first post (question) here, so please don't judge me.
I'm trying to build my first individual WCF service for my project. Let me first display my code , so it will be easier to understand.
This is my data access layer:
public class DataAccessLayer : IDisposable
{
string DBConnectionString = "DBCS";
public int ValidateUser(string employeeLogin, string employeePassword)
{
int outputResult = 0;
try
{
DatabaseProviderFactory factory = new DatabaseProviderFactory();
Database db = factory.Create(DBConnectionString);
string storedProcedureName = "uspValidateUser";
DbCommand dbCommand = db.GetStoredProcCommand(storedProcedureName);
db.AddInParameter(dbCommand, "#EmployeeLogin", DbType.String, employeeLogin);
db.AddInParameter(dbCommand, "#EmployeePassword", DbType.String, employeePassword);
db.AddOutParameter(dbCommand, "#OutRes", DbType.Int32, outputResult);
using (IDataReader reader = db.ExecuteReader(dbCommand))
{
Mapper.Reset();
Mapper.CreateMap<IDataReader, Int32>();
outputResult = (int)Mapper.Map<IDataReader, Int32>(reader);
}
}
catch (Exception ex)
{
throw ex;
}
return outputResult;
}
public void Dispose()
{
}
}
This is my stored procedure:
ALTER PROCEDURE [dbo].[uspValidateUser]
#EmployeeLogin VARCHAR(20),
#EmployeePassword VARCHAR(20),
#OutRes int Output
AS
SET #OutRes = (select count(*)
from dbo.tblEmployee
where EmployeeLogin = #EmployeeLogin
and EmployeePassword = #EmployeePassword)
if (#OutRes = 1)
BEGIN
SET NOCOUNT ON;
set #OutRes = 1 --Login is correct
end
else
BEGIN
set #OutRes = 0 -- Login is incorrect
END
And code behind my web form:
public int ValidateUser(string employeeLogin, string employeePassword)
{
int outputResults = 0;
try
{
using (HospitalWCFService.ContractsClient objWCFService = new HospitalWCFService.ContractsClient())
{
outputResults = objWCFService.ValidateUser(employeeLogin, employeePassword);
}
}
catch (Exception ex)
{
lgnEmployeeLogin.FailureText = ex.Message;
}
return outputResults;
}
protected void ValidateUser(object sender, AuthenticateEventArgs e)
{
int outputResults = 0;
outputResults = ValidateUser(lgnEmployeeLogin.UserName, lgnEmployeeLogin.Password);
if (outputResults == 1)
{
Session["UserName"] = lgnEmployeeLogin.UserName.ToString();
FormsAuthentication.RedirectFromLoginPage(lgnEmployeeLogin.UserName, lgnEmployeeLogin.RememberMeSet);
}
else
{
lgnEmployeeLogin.FailureText = "Username and/or password is incorrect.";
}
}
To get user credentials I'm using login control lgnEmployeeLogin.
I'm having problems of retrieving that output integer #OutRes parameter from database using Mapper (I need to use mapper)
If it is possible, please explain solution in easiest language possible as I might not understand difficult technical slang.
Thank you all in advance!
Your lack of answers could be because you say that you have to use mapper - but I chose to ignore that, because ExecuteReader is for dealing with the rows and columns returned by a stored procedure, not for its output parameters. The stored procedure you provided has no result set!
This could be as simple as
db.ExecuteNonQuery();
OutputResult = db.Parameters( "#OutRes").value
to be clear, this replaces your using...ExecuteReader block
Also note: your code did not deal with opening (and closing) the SQL connection (db.Connection.Open();, so I ignored that here too.

Sqlite insertOrThrow() failing with database file not found error

I'm having a hard time getting any of the inserts to work with SqlLite. I have a table created with the following schema:
create table drink_category ( _id integer not null primary key autoincrement, value unique);
When the attached code runs, I get a SQLiteCantOpenDatebaseException with the error message "cannot open database file (code 14)".
As you can see in the code, I access the table with a query without a problem. I also do a db.isOpen() to verify the database is OK. I have even added code after the block with the insert and everything works OK. Any help would be greatly appreciated.
public Boolean add(String strValue)
{
Boolean bStatus = true;
String strSql;
String sqlValue = strValue.replaceAll("'","\'\'");
if (bStatus)
{
if (strValue.isEmpty())
{
BarDB.getInstance().setErrorMessage("No value entered.");
bStatus = false;
}
}
if (bStatus)
{
strSql = "select value from " + "drink_category" + " where value = '" + sqlValue + "' ";
Cursor cursor = SqlDbAdapter.getInstance().getDatabase().rawQuery(strSql, null);
if (null == cursor)
{
BarDB.getInstance().setErrorMessage("Problem with the database.");
bStatus = false;
}
else if (cursor.getCount() > 0)
{
BarDB.getInstance().setErrorMessage("A Drink Category with that name already exists.");
bStatus = false;
}
}
if (bStatus)
{
ContentValues cvValues = new ContentValues();
cvValues.put("value", sqlValue);
SQLiteDatabase db = SqlDbAdapter.getInstance().getDatabase();
if (db.isOpen())
{
try
{
long lerror = db.insertOrThrow("drink_category", null, cvValues);
}
catch (SQLiteException sqle)
{
BarDB.getInstance().setErrorMessage(sqle.toString());
bStatus = false;
}
}
}
return bStatus;
}
FOUND IT: I am running this on an emulator and I was storing the database file in /data/data. I guess when you do an insert, sqlite needs to write to a journal file and that directory is read only. I moved the database to /data/data//databases and things are working OK now. A better error message would have been much more helpful!

Resources