Sqlite insertOrThrow() failing with database file not found error - sqlite

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!

Related

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?

How to move Resultset curser via button click, and display data in textfields?

So, I'm creating a desktop banking application. It's nothing too serious, I'm just trying to practice and get better.
// Method I use to get a connection. I know this works.
public static Connection getConnection() throws SQLException {
String sCon = "jdbc:sqlite:banking.sqlite";
Connection connection = DriverManager.getConnection(sCon);
return connection;
}
.
..
...
.....Other code
Method I attempt to use to create and manipulate the data in the result set.
The problem I believe starts here. With this code, I am only able to return one row of the result set and only the last row.
public static Customers getAccounts(Customers c) {
String query = "select RowCount, Customers.Account_Number, "
+ "Customers.First_Name, Last_Name, Address, "
+ "Phone_Number, Accounts.Balance "
+ "from Customers "
+ "join Accounts ";
try (Connection connection = getConnection();
PreparedStatement ps = connection.prepareStatement(query);
ResultSet rs = ps.executeQuery()) {
while (rs.next()) {
String fName = rs.getString("First_Name");
String lName = rs.getString("Last_Name");
String address = rs.getString("Address");
String phone = rs.getString("Phone_Number");
String accNum = rs.getString("Account_Number");
String balance = rs.getString("Balance");
c.setFirstName(fName);
c.setLastName(lName);
c.setAddress(address);
c.setPhoneNumber(phone);
c.setAccountNumber(accNum);
c.setBalance(balance);
}
return c;
} catch (SQLException e) {
System.err.println(e);
}
return null;
}
}
Here is the method that is linked to the button I use to perform what I'm trying to attempt. It's part of the Controller class. I believe this method is also a part of the problem. Any ideas? Thank for all you guys do. This website is a real benefit to the community.
public void next() {
Customers c = new Customers();
DBInterface.getAccounts(c);
firstNameF2.setText(c.getFirstName());
lastNameF2.setText(c.getLastName());
addressF2.setText(c.getAddress());
phoneNumberF2.setText(c.getPhoneNumber());
accNumF.setText(c.getAccountNumber());
balanceF.setText(c.getBalance());
}
If you are expecting to get multiple Customers objects, then you definitely should return a list of that.
public static List<Customers> getAccounts() {
// Whatever you originally had...
final List<Customers> ret = new ArrayList<>();
while (rs.next()) {
String fName = rs.getString("First_Name");
String lName = rs.getString("Last_Name");
String address = rs.getString("Address");
String phone = rs.getString("Phone_Number");
String accNum = rs.getString("Account_Number");
String balance = rs.getString("Balance");
final Customers cust = new Customers();
cust.setFirstName(fName);
cust.setLastName(lName);
cust.setAddress(address);
cust.setPhoneNumber(phone);
cust.setAccountNumber(accNum);
cust.setBalance(balance);
ret.add(cust);
}
return ret;
}
I have removed the part about passing in the instance of Customers (which would have ended up as passing in List<Customers>. If you really need to do that, you can add back in and do all the necessary checks.

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.

Entity Framework Error

I have a little problem. I am encountering the following error each time I try update my entityset.
Unable to update the EntitySet 'ShoppingCart' because it has a
DefiningQuery and no InsertFunction element exists in the
ModificationFunctionMapping element to support the current
operation.
The code is: `
public void AddItem(string cartID, string productID, string quantity)
{
using (CommerceEntities db = new CommerceEntities())
{
try
{
var myItem = (from c in db.ShoppingCarts
where c.CartID == cartID &&
c.ProductID == productID
select c).FirstOrDefault();
if (myItem == null)
{
ShoppingCart cartadd = new ShoppingCart();
cartadd.CartID = cartID;
cartadd.Quantity = quantity;
cartadd.ProductID = productID;
cartadd.DateCreated = DateTime.Now;
db.ShoppingCarts.AddObject(cartadd);
}
else
{
myItem.Quantity += Convert.ToInt32(quantity);
}
db.SaveChanges();
}
catch (Exception exp)
{
throw new Exception("ERROR: Unable to Add Item to Cart - " +exp.Message);
}
}
}
`
Please help me. I can provide more information if required, I am new to this Entity Framework Model and following the tutorial on This page.
Update: I added primary keys and redesigned the whole database. Now the error changed to:
System.Data.UpdateException was unhandled by user code Message=An
error occurred while updating the entries. See the inner exception for
details.
This usually happens if entity set is mapped from database view, custom database query or if database table doesn't have primary key.

Unable to search through encrypted value from sqlite database

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.

Resources