Blackberry - Cant see always db in sd card emulator - database

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.

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.

Check MySql Connection is Opened Or Not in Visual C++

Sorry, If u filling bored. I have searched on several search engines but could not got any result. Anyway I am working in an App which database is mysql. Now I have created a database wrapper class and want to check if the connection is already opened. Could u help me?
String^ constring = L"datasource=localhost;port=3306;username=root;password=pass;database=eps;";
String^ my_query = L"select id from eps_users where usr = '" + this->user_name->Text + "' and psw = md5('" + this->pass_word->Text + "');";
MySqlConnection^ conDatabase = gcnew MySqlConnection(constring);
MySqlCommand^ cmd = gcnew MySqlCommand(my_query, conDatabase);
MySqlDataReader^ myreader;
try
{
conDatabase->Open();
myreader = cmd->ExecuteReader();
int count = 0;
while (myreader->Read())
{
count = count + 1;
}
if (count == 1){
MessageBox::Show("Username And Password is correct.", "Success", MessageBoxButtons::OK,
MessageBoxIcon::Information);
this->Hide();
Form2^ f2 = gcnew Form2(constring);
f2->ShowDialog();
}
else{
MessageBox::Show("Username And Password is not correct.", "Error", MessageBoxButtons::OK,
MessageBoxIcon::Error);
// <del>
this->Hide();
Form2^ f2 = gcnew Form2(constring);
f2->ShowDialog();
// </del>
}
}
catch (Exception^ ex)
{
MessageBox::Show(ex->Message);
}
conDatabase->Close();
I need to check if( conDatabase->HasBeenOpened()) { conDatabase->Open();}
The MySqlConnection type implements a feature called connection pooling that relies on the garbage collector to help recycle connections to your database, such that the best practice with regards to connection objects is to create a brand new object for most calls to the database, so that the garbage collector can correctly recycle the old ones. The process goes like this:
Create a new connection
Open the connection
Use the connection for one query/transaction
Dispose the connection
Where all four steps live within a single try/catch/finally block. (Also, the dispose step needs to happen inside the finally block!) Because you generally start with a brand new connection object, there's not typically a need to check if it's open first: you know it's closed. You also don't need to check the state after calling Open(): the method will block until it's finished, and throw an exception if it fails.
However, if you really are in one of the (rare!) situations where it's a good idea to preserve the connection for an extended period, you can check the state like this:
if( conDatabase->State == ConnectionState::Open)
Now, there is one other issue in that code I'd like to talk about. The issue comes down to this: what do you think will happen if I put the following into your username text box:
';DROP Table eps_users;--
If you think that it will try to execute that DROP statement in your database, you're right: it will! More subtle and damaging queries are possible, as well. This is a huge issue: there are bots that run full time crawling web sites looking for ways to abuse this, and even an corporate internal desktop apps will get caught from time to time. To fix this, you need to use Parameterized Queries for every instance where include user-provided data as part of your sql statement.
A quick example might look like this:
String^ my_query = L"select id from eps_users where usr = #userID;";
MySqlCommand^ cmd = gcnew MySqlCommand(my_query, conDatabase);
cmd->Parameters->AddWithValue(L"#userID", this->user_name->Text);

Very strange lin2sql error

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.

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