Very strange lin2sql error - database

The problem is "after inserting a data using linq2sql & do submit changes , I cant find the data in database " I will explain more :
first here's my DB design :
I made sure that I got primary keys for auto insert
I made sure that the data context is in the same path as my .mdb file lies
I used server explorer in VS2010 to check for the DB data
Here's the function I use to insert a simple data:
public static bool add_contractor(string name,string ssn, string address)
{
Contractor co = new Contractor();
co.co_address = address;
co.co_name = name;
co.co_ssn = ssn;
db.Contractors.InsertOnSubmit(co);
try
{
db.SubmitChanges();
}
catch (Exception)
{
return false;
}
return true;
}
I did debugging & checked for the function , I got no error on submitting & the data should be submitted .
While I'm running the [program & using the following function to get the data from the table "contractor" :
public static Contractor[] get_contractors()
{
var ret = from p in db.Contractors
select p;
return ret.ToArray<Contractor>();
}
then displaying it I found the data I inserted ... great till now ,
I go to server explorer & check for the data but I don't find it .... strange huh
I use the function again & it tells me that the data I inserted exists....
The moment I close my program & re run it I dont find the data I inserted .

You mentioned you are using an mdb file, if it is set to copy always, every time you debug it will overwrite it. Hence no data when you run it again.
Try placing the file outside the project and point your connection string to that, see if the data persists.

Related

Create persistent Sqlite db in Windows phone 8

I am trying my hands on Windows phone 8 applications and I am stuck into a weird situation here. I am using sqlite in order to create sqlite db and add values into the database. I am able to create the database and add the values in the database successfully but I am having a weird situation here.
Everytime I close the emulator and start the project again the database gets created again which should not be happening because I created the db the very first time I run the application.
Does anybody know why, and how I can prevent it from recreating the database each time?
public string DB_PATH = Path.Combine(Path.Combine(ApplicationData.Current.LocalFolder.Path, "aa.sqlite"));
private SQLiteConnection dtCon;
public MainPage()
{
InitializeComponent();
CreateDatabase();
dtCon = new SQLiteConnection(DB_PATH);
var tp = dtCon.Query<Contacts>("select * from contacts").ToList();
}
private async void CreateDatabase()
{
bool isDatabaseExisting = false;
//Checking if database already exists
try
{
Windows.Storage.StorageFile storagefile = await Windows.Storage.ApplicationData.Current.LocalFolder.GetFileAsync("aa.sqlite");
isDatabaseExisting = true;
}
catch
{
isDatabaseExisting = false;
}
//if not exists then creating database
if (!isDatabaseExisting)
{
String str = System.IO.Path.Combine(Windows.Storage.ApplicationData.Current.LocalFolder.Path, "sqlite.db");
AddDataToDB(DB_PATH);
}
}
private void AddDataToDB(string str)
{
// Create the database connection.
dtCon = new SQLiteConnection(str);
// Create the table Task, if it doesn't exist.
dtCon.CreateTable<Contacts>();
Contacts oContacts = new Contacts();
oContacts.Name = "dfgdf";
oContacts.Detail = "asdfsf";
dtCon.Insert(oContacts);
}
I'm pretty sure when you close your emulator and restart, you're basically just uninstalling the application. Which is why your files or not there anymore -- as it looks like you're storing your data in isolated storage. I do not know if there is anyway around this.
You can buy a very cheap Windows 8/8.1 Phone and the files will persist until you manually uninstall the test application.
As #Chubosaurus says, closing and re-opening the emulator will remove all the apps. You can generally keep it running as long as you want and keep re-deploying your app to the emulator (although obviously rebooting the host PC will kill it).
You can save and restore the data from your emulator image via the ISETool command. See more here
Try adding Console.WriteLine("True"); and Console.WriteLine("False"); into the expected places after checking isDatabaseExisting to see/understand what the code path really is.

What is my embedded database location

Hello I am having problems with testing if my embedded datbase exists.
I created a database like follows:
try {
SQLiteConnection.CreateFile("AttendanceDatabase.sqlite");
} catch (SQLiteException ex) {
}
And then I insert tables and data into the tables, everything works fine. When im saving data to the database im using the the connection string as follows:
conn = new SQLiteConnection("Data Source=AttendanceDatabase.sqlite;Version=3;");
Now my problem is everytime I run my program it creates the database over, and I would like to know how to test if the database exists it should not create the database over again.
I see the recomended way to do it is using the next statement:
if (File.Exists())
{
}
and I have tried using it as follows:
if (File.Exists("Data Source=AttendanceDatabase.sqlite;Version=3;")){
MessageBox.Show("File Exists");
}
but it does not want to go into the if brackets and display "File Exists".
So I would like to know what my path should be for my embedded database, that is if thats where my problem lies?
Thanx in advance!
I don't have a ton of context but if you update your check:
var basePath = "C:/<path to file>/";
if (File.Exists(basePath + "AttendanceDatabase.sqlite")){
MessageBox.Show("File Exists");
}
You might have more luck. If you give me more context to how you are running this I can help you with using services to lookup the file path. You can look it up based on assembles, approot, etc.

Blackberry - Cant see always db in sd card emulator

I dont know what's happenning.
This is my code:
public class MyApp extends MainScreen {
Database sqliteDB;
URI uri;
String name;
public MyApp()
{
try{
uri = URI.create("file:///SDCard/Databases/sample/" +"prueba.db");
sqliteDB = DatabaseFactory.create(uri);
sqliteDB = DatabaseFactory.open(uri);
Statement st = sqliteDB.createStatement("CREATE TABLE joke(name)");
st.prepare();
st.execute();
st.close();
Statement st1 = sqliteDB.createStatement("INSERT INTO joke VALUES ('Maxo')");
st1.prepare();
st1.execute();
st1.close();
Statement st2 = sqliteDB.createStatement("INSERT INTO joke VALUES ('Lala')");
st2.prepare();
st2.execute();
st2.close();
/*
Statement st1 = sqliteDB.createStatement("SELECT * from joke");
st1.prepare();
Cursor c = st1.getCursor();
Row r;
while(c.next()) {
r = c.getRow();
name = r.getString(0);
}
st1.execute();
st1.close();*/
sqliteDB.close();
add(new RichTextField("Status: Database was created and inserted the values successfully"));
//add(new RichTextField(""+name));
}
catch (Exception e){
System.out.println(e.getMessage());
e.printStackTrace();
}
}
}
Im just creating a database, a table and inserting two fields. So what i do is first execute emulator, set a directory to my sdcard. Well after that i execute my program, and sometimes it creates the database in that directoy, sometimes not, sometimes it creates database without table or data.. i dont know why, i tried 8520 9550 emulator, but its rare whats happenning with database and sdcard. Anyone has an idea of what could be happenning? Its annoying to be coding and sometimes it works sometimes not and you dont know why.. And its not coding problem i think, because sometimes it works :S
Make sure u have mounted your SD card.Double click on the folder where you want to save your database and then tick the checkbox for remounting it on next emulator run.
Hope it helps.

How to use my own sqlite database?

I put my database field in "assets" folder. And use the code from this blog to copy the database to "/data/data/my_packname/databases/", (This copy code i run it in the onCreate() method when i run this app) then use select * from ... to get data. But it gives me the exception: no such table.
Someone told me that if i am attempting to copy the file in SQLiteOpenHelper's onCreate(), it's too late. So the copy file code can not copy the complete file.
So i need to use adb or ddms to pull the database first?
So, Anyone can teach me how to use my own databse?
Can you tell me the setup?
I've used the instructions in that blog post and found them, while on the right track, to severely complicate the issue by unnecessarily extending SQLiteOpenHelper. I've had much better luck doing the following:
Create a utility class that creates the static db by copying it into the correct directory from assets, but doesn't get itself so hung up on following the SQLiteOpenHelper format.
Using the same utility class to open the db by using SQLiteDatabase.openDatabase()
Edit: Here is a version of this utility class I've created; it's not quite complete, but you'll get the drift.
public class DbUtils {
private static final String DB_PATH = "/data/data/com.mypackage.myapp/databases/";
private static final String DB_NAME = "my.db";
public static void createDatabaseIfNotExists(Context context) throws IOException {
boolean createDb = false;
File dbDir = new File(DB_PATH);
File dbFile = new File(DB_PATH + DB_NAME);
if (!dbDir.exists()) {
dbDir.mkdir();
createDb = true;
}
else if (!dbFile.exists()) {
createDb = true;
}
else {
// Check that we have the latest version of the db
boolean doUpgrade = false;
// Insert your own logic here on whether to upgrade the db; I personally
// just store the db version # in a text file, but you can do whatever
// you want. I've tried MD5 hashing the db before, but that takes a while.
// If we are doing an upgrade, basically we just delete the db then
// flip the switch to create a new one
if (doUpgrade) {
dbFile.delete();
createDb = true;
}
}
if (createDb) {
// Open your local db as the input stream
InputStream myInput = context.getAssets().open(DB_NAME);
// Open the empty db as the output stream
OutputStream myOutput = new FileOutputStream(dbFile);
// transfer bytes from the inputfile to the outputfile
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer)) > 0) {
myOutput.write(buffer, 0, length);
}
// Close the streams
myOutput.flush();
myOutput.close();
myInput.close();
}
}
public static SQLiteDatabase getStaticDb() {
return SQLiteDatabase.openDatabase(DB_PATH + DB_NAME, null, SQLiteDatabase.OPEN_READONLY);
}
}
After you've copied the database, you should try closing and reopening the SQLiteDatabase object before executing any query on it. I had a similar problem with copying a db from an input stream and that's what solved it for me.
here is my Version from "Silvio Donnini" Code :),
now you can update the Database easily.
private static final String DB_PATH = "/data/data/pakagename/databases/";
private static final String DB_NAME = "databaseName";
private static SQLiteDatabase db;
public static void createDatabaseIfNotExists(Context context,int version) throws IOException {
boolean createDb = false;
File dbDir = new File(DB_PATH);
File dbFile = new File(DB_PATH + DB_NAME);
if (!dbDir.exists()) {
dbDir.mkdir();
createDb = true;
}
else if (!dbFile.exists()) {
createDb = true;
}
else {
// Check that we have the latest version of the db
db = SQLiteDatabase.openDatabase(DB_PATH + DB_NAME, null, SQLiteDatabase.OPEN_READONLY);
if (db.getVersion() != version) {
dbFile.delete();
createDb = true;
}
}
if (createDb) {
// Open your local db as the input stream
InputStream myInput = context.getResources().openRawResource(R.raw.database);
// Open the empty db as the output stream
OutputStream myOutput = new FileOutputStream(dbFile);
// transfer bytes from the inputfile to the outputfile
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer)) > 0) {
myOutput.write(buffer, 0, length);
}
// Close the streams
myOutput.flush();
myOutput.close();
myInput.close();
SQLiteDatabase dbwrite = SQLiteDatabase.openDatabase(DB_PATH + DB_NAME, null, SQLiteDatabase.OPEN_READWRITE);
dbwrite.setVersion(version);
dbwrite.close();
if (db != null)
db = SQLiteDatabase.openDatabase(DB_PATH + DB_NAME, null, SQLiteDatabase.OPEN_READONLY);
}
}
public static SQLiteDatabase getStaticDb() {
if (db != null)
return db;
return SQLiteDatabase.openDatabase(DB_PATH + DB_NAME, null, SQLiteDatabase.OPEN_READONLY);
}
I know this is an old question, but I lost a lot of time figuring it out, with the help of all the replies.
The issue is that a device stores a database in his data/data/.../databases folder. So, when you change sth about the database (name, add android metadata table, size..) it wont make any difference because of the stored database and the method that checked for existing database.
To get the newest database, after changing it, you must run the program without checking for existing databses (e.g. instead of dbExist = checkDataBase(); make it just false).
dbExist = checkDataBase();
Change to:
dbExists = false;
After you picked up the "new" databse you can return to checking the existing ones.
Hope it helps someone,
dina
I know this is an old post, but for those who still get here after a Google or a Bing search, this is the solution to the stated problem:
in createDataBase() there is the following check;
this.getReadableDatabase();
This checks if there is already a database with the provided name and if not creates an empty database such that it can be overwritten with the one in the assets folder. On newer devices this works flawlessly but there are some devices on which this doesn't work. Mainly older devices. I do not know exactly why, but it seems like the getReadableDatabase() function not only gets the database but also opens it. If you then copy the database from the assets folder over it, it still has the pointer to an empty database and you will get table does not exist errors.
So in order to make it work on all devices you should modify it to the following lines:
SQLiteDatabase db = this.getReadableDatabase();
if (db.isOpen()){
db.close();
}
Even if the database is opened in the check, it is closed thereafter and it will not give you any more trouble.
Calm down guys,After long research finally found silly mistake for "no such table" error
Check name of database in Assets folder if it's like "DATABASE_NAME.EXTENSION" then put full name in Helper class with extension its solved my problem.
like say in Assets name of database is login.sqlite or login.db anything. put DB_NAME=login.sqlite fully with extention.
this tutorial now works perfectly.
The way of creating database from article you've posted is slightly diffrent from that how it's done in android examples (I don't want to say if it's good or bad).
I've learned how to use databases from SDKs NotePad sample
It's good example to start from, becouse it covers both database creation topic and database access through ContentProvider (it's really the only good way to get data from db, otherwise you will have problems when trying to get data simultaneusly from many places of your code).
You should note that SQLiteOpenHelper is really powerful and "it will help you" if you will use it properly. For example it stores current database version (not sqlite version but number you assingn with database schema version) and when you create new application version with new database structure you can update current schema to the new version in onUpdate.

The file 'C:\....\.....\.....\bin\debug\128849991926295643' already exists

I'm using Visual C#2008 Express Edition and an Express SQL database. Every time I build my solution, I get an error like the one above. Obviously the file name changes. A new file is also created every time I hit a debug point.
I have a stored proc that gets every row from a database table, it gets these rows every time the main form initialises and Adds them to a Generics list. Without inserting or deleting from the table, it gets a different number of rows each time I start my windows application. The error started happening at the same time as the weird data retrieval issue. Any ideas at all about what can cause this?
Thanks
Jose,
Sure, here's my c# method, it retrieves every row in my table, each row has an int and and Image ....
private List<ImageNumber> GetListOfKnownImagesAndNumbers()
{
//ImageNumber imNum = new ImageNumber();
SqlCommand sqlCommand = new SqlCommand();
sqlCommand.Connection = _conn;
try
{
MemoryStream ms = new MemoryStream();
sqlCommand.CommandText = "usp_GetKnownImagesAndValues";
_conn.Open();
using (IDataReader dr = sqlCommand.ExecuteReader())
{
while (dr.Read())
{
ImageNumber imNum = new ImageNumber();
imNum.Value = dr.IsDBNull(dr.GetOrdinal("ImageValue")) ? 0 : Convert.ToInt32(dr["ImageValue"]);
//Turn the bitmap into a byte array
byte[] barrImg = (byte[])dr["ImageCaptured"];
string strfn = Convert.ToString(DateTime.Now.ToFileTime());
FileStream fs = new FileStream(strfn,
FileMode.CreateNew, FileAccess.Write);
fs.Write(barrImg, 0, barrImg.Length);
fs.Flush();
fs.Close();
imNum.Image = (Bitmap)Image.FromFile(strfn);
_listOfNumbers.Add(imNum);
}
dr.Close();
_conn.Close();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
_conn.Close();
}
return _listOfNumbers;
}
And here's my stored proc....
ALTER PROCEDURE dbo.usp_GetKnownImagesAndValues
AS
BEGIN
select ImageCaptured, ImageValue
from CapturedImages
END
Thanks for looking at this. The answer in the end was to put a Thread.Sleep inside the while loop and it started working perfectly. There may be something else I could do, I am obviously waiting for something to complete which is why allowing more time has helped here. If I knew what needed to complete and how to detect when it had completed then I could check for that instead of simply waiting for a short time.

Resources