I'm developing an application for my WindowsCE packect PC(.netCF35) to read some parameters and record them in my SQLite database in Visual Studio 2008. I knew that I need to add SQLite references to my application (I had a succeed experience for my windows 7 application). So I downloaded related files from http://system.data.sqlite.org/index.html/doc/trunk/www/downloads.wiki and I just could add System.Data.SQLite.dll (I couldn't add SQLite.Interop.102.dll to my references). Now when I run my application, I can't add any data to my database and it seems cmdwrite.ExecuteNonQuery(); doesn't work correct. I need to say my table name and structure is correct(I'm sure). You can see my code as follow:
SQLiteConnection con = new SQLiteConnection("Data Source=AMI.sqlite;Version=3;");
public bool Insert(string Meter_ID, string type, string readout, string timestamp)
{
sqlwrite = "INSERT INTO meters (id,type,val,timestamp) VALUES(?,?,?,?)";
try
{
SQLiteCommand cmdwrite = new SQLiteCommand(sqlwrite, con);
cmdwrite.Parameters.AddWithValue("#id", Meter_ID);
cmdwrite.Parameters.AddWithValue("#type", type);
cmdwrite.Parameters.AddWithValue("#val", readout);
cmdwrite.Parameters.AddWithValue("#timestamp", timestamp);
con.Open();
dbstate = "3";
cmdwrite.ExecuteNonQuery();
dbstate = "4";
con.Close();
return true;
}
catch
{
con.Close();
return false;
}
}
Insert("123", "456", "789", "123");
Does anybody have any experience to work with SQLite database in WindowsCE?
Related
I am building a inventory based application that can be directly run from any pc without any installation and so i am using SQL CE.. On Start, I am checking if database is present. If Not i am creating new database as :
try
{
string conString = "Data Source='ITM.sdf';LCID=1033;Password=ABCDEF; Encrypt = TRUE;";
SqlCeEngine engine = new SqlCeEngine(conString);
engine.CreateDatabase();
return true;
}
catch (Exception e)
{
//MessageBox.Show("Database Already Present");
}
The database is created properly and i can access the database to create tables as well.. The Problem i am facing is - I am inserting and updating records in windows form on button click with code :
using (SqlCeConnection connection = new SqlCeConnection(DatabaseConnection.connectionstring))
{
connection.Open();
String Name = NameTxt.Text.ToString();
String Phone = PhoneTxt.Text.ToString();
double balance = Double.Parse(BalanceTxt.Text.ToString());
String City = CityTxt.Text.ToString();
string sqlquery = "INSERT INTO Customers (Name,Phone,Balance,City)" + "Values(#name,#phone, #bal, #city)";
SqlCeCommand cmd = new SqlCeCommand(sqlquery, connection);
cmd.Parameters.AddWithValue("#name", Name);
cmd.Parameters.AddWithValue("#phone", Phone);
cmd.Parameters.AddWithValue("#bal", balance);
cmd.Parameters.AddWithValue("#city", City);
int x = cmd.ExecuteNonQuery();
if (x > 0)
{
MessageBox.Show("Data Inserted");
}
else
{
MessageBox.Show("Error Occured. Cannot Insert the data");
}
connection.Close();
}
and Updation Code is
using (SqlCeConnection connection = new SqlCeConnection(DatabaseConnection.connectionstring))
{
connection.Open();
int idtoedit = select_id_edit;
String Name = NameEditTxt.Text.ToString();
String Phone = metroTextBox1.Text.ToString();
String City = CityEditTxt.Text.ToString();
string sqlquery = "Update Customers Set Name = #name, Phone = #phone,City = #city where Id = #id";
SqlCeCommand cmd = new SqlCeCommand(sqlquery, connection);
cmd.Parameters.AddWithValue("#name", Name);
cmd.Parameters.AddWithValue("#phone", Phone);
cmd.Parameters.AddWithValue("#id", idtoedit);
cmd.Parameters.AddWithValue("#city", City);
int x = cmd.ExecuteNonQuery();
if (x > 0)
{
MessageBox.Show("Data Updated");
}
else
{
MessageBox.Show("Error Occured. Cannot Insert the data");
}
loadIntoGrid();
connection.Close();
}
Whenever i execute code for inserting and updating records - Records are reflected in datagrid filled with adapter from database table. But once i restart the application, values do not appear in database. Once in a million, values are reflected in database. I cannot understand the reason behind this issue.
I have reffered to these articles :
C# - ExecuteNonQuery() isn't working with SQL Server CE
Insert, Update, Delete are not applied on SQL Server CE database file for Windows Mobile
But since i am creating database programmatically - It is getting created directly to bin/debug directory and i cannot see it in solution explorer in visual studio for changing copy options
You probably rewrite your database file with a blank copy from your project.
See this answer. You should not store your database in a bin folder, rather you should find a place in user's or public profile in AppData or another folder, depending on your needs.
The connection string would look like this:
<connectionStrings>
<add name="ITMContext" connectionString="data source=|DataDirectory|\ITM.sdf';LCID=1033;Password=ABCDEF; Encrypt = TRUE;" providerName="System.Data.SqlServerCe.4.0">
You shuld deploy your db file with your custom code run at app's starup to a chosen location, see this ErikEJ blog: http://erikej.blogspot.cz/2013/11/entity-framework-6-sql-server-compact-4_25.html
private const string dbFileName = "Chinook.sdf";
private static void CreateIfNotExists(string fileName)
{
string path = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
// Set the data directory to the users %AppData% folder
// So the database file will be placed in: C:\\Users\\<Username>\\AppData\\Roaming\\
AppDomain.CurrentDomain.SetData("DataDirectory", path);
// Enure that the database file is present
if (!System.IO.File.Exists(System.IO.Path.Combine(path, fileName)))
{
//Get path to our .exe, which also has a copy of the database file
var exePath = System.IO.Path.GetDirectoryName(
new Uri(System.Reflection.Assembly.GetExecutingAssembly().CodeBase).LocalPath);
//Copy the file from the .exe location to the %AppData% folder
System.IO.File.Copy(
System.IO.Path.Combine(exePath, fileName),
System.IO.Path.Combine(path, fileName));
}
}
Check also this post.
You have several options to change this behavior. If your sdf file is
part of the content of your project, this will affect how data is
persisted. Remember that when you debug, all output of your project
(including the sdf) if in the bin/debug folder.
You can decide not to include the sdf file as part of your project and manage the file location runtime.
If you are using "copy if newer", and project changes you make to the database will overwrite any runtime/debug changes.
If you are using "Do not copy", you will have to specify the location in code (as two levels above where your program is running).
If you have "Copy always", any changes made during runtime will always be overwritten
The database file in your project can be different when debugging or not. Check also this answer. You might be writting your records to another copy of the database file.
I am building a win form application in c# which will be installed on windows server 2008. All users that will be using this application connects with their username and password using remote desktop connection. What happens if two or more users opens this application? Will it work correctly for all user? or it become race condition ( who gets first wins? :) ) what do I need to do to make it work correctly for all users? maybe I need to create System.Net.Sockets or something else?
UPDATED:
Code to select data from table and then update it:
DuomenysDataSet ds; //dataset which was created when I create a database on visual studio
public static string ID { get; set; }
private void FillDataGrid()
{
try
{
SqlCommand command = new SqlCommand("SELECT PirminiaiNuo,PirminiaiIki,Ikainis,MenesinisMokestis,Metine FROM \"" + ID + "\"", DBConnection);
ds = database.FillData(command, "Ikainiai"); // "Ikainiai" = DataSet table name
IkainiaiView.Columns[0].DataPropertyName = "PirminiaiNuo";
IkainiaiView.Columns[1].DataPropertyName = "PirminiaiIki";
IkainiaiView.Columns[2].DataPropertyName = "Ikainis";
IkainiaiView.Columns[3].DataPropertyName = "MenesinisMokestis";
IkainiaiView.Columns[4].DataPropertyName = "Metine";
IkainiaiView.Enabled = false;
IkainiaiView.DataSource = ds.Tables[a];
IkainiaiView.Enabled = true;
}
To update table I pass same SqlCommand and table name to the database class method updateTable code below:
public void updateDatabase(SqlCommand command, string tableName)
{
sql = new SqlDataAdapter(command);
sql.SelectCommand = command;
sql.SelectCommand.Connection = Connection();
SqlCommandBuilder c = new SqlCommandBuilder(sql); // not sure if this is necessary
sql.Update(ds.Tables[tableName]);
}
Code to create a new table: here ID is the AutoIncrement id from different table (primary key) this is why it is not a parameter.
public static string ID { get; set; }
private void Kainininkas_Load(object sender, EventArgs e)
{
SqlCommand command = new SqlCommand("SELECT * INTO \"" + ID + "\" FROM IkainiuSablonasPilnas", DBConnection);
try
{
DBConnection.Open();
command.ExecuteNonQuery();
DBConnection.Close();
}
catch (Exception ex)
{
TopMostMessageBox.Show(ex.Message);
}
}
To insert new rows to the table i use this code:
DBConnection = database.Connection();
SqlCommand command = new SqlCommand("INSERT INTO Imones (Imone,Adresas,ImonesKodas,PVMKodas,Vykdytojas,Musu,SutartiesNr,SutartiesData,Sutartis,Active,Buhalteris) VALUES (#Imone,#adresas,#ImonesKodas,#PVMKodas,#Vykdytojas,'',#SutartiesNR, #SutartiesData,#Sutartis,#Active,#Buhalteris);", DBConnection);
command.Parameters.AddWithValue("#Imone", textBox1.Text);
command.Parameters.AddWithValue("#adresas", textBox2.Text);
command.Parameters.AddWithValue("#ImonesKodas", UzsakovasImonesKodasText.Text);
command.Parameters.AddWithValue("#PVMKodas", textBox4.Text);
command.Parameters.AddWithValue("#Vykdytojas", ImoniuSarasasCmb.Text);
command.Parameters.AddWithValue("#SutartiesNR", textBox3.Text);
command.Parameters.AddWithValue("#SutartiesData", dateTimePicker1.Text);
command.Parameters.Add("#Sutartis", SqlDbType.Binary).Value = buff;
command.Parameters.AddWithValue("#Active", aktyvi);
command.Parameters.AddWithValue("#Buhalteris", comboBox1.Text);
command.ExecuteNonQuery();
As long as the app isn;t locking physical resources (files) while another copy tries to use them, you can open/use multiple copies of your winforms app at the same time.
EDIT
As an extra note, thanks to CodeCaster, if you implement a file based db access routine, that may lock the file when accessing the DB file, you could run into issues. If you use a service level DB implementation, like SQL Express, then there should not be any issues with running multiple copies of the app.
As a last note, its perfectly normal for an application to run as multiple copies on the same Application server. Think about, Ms Word, Exel, Outlook, Adobe Reader, Windows Explorer...
Just make sure you take the above points into account.
Hi all I have an small application to add the expense of the day.
For this I am using SQL compact database (CE). While inserting the record into a table name Expenses I am getting error
The specified table does not exist. [Expenses]
Insertion code is
using (var con =new SqlCeConnection(#"Data Source=|DataDirectory|\Database\Acadamy.sdf;
Persist Security Info=False"))
{
con.Open();
try
{
var Cmd = new SqlCeCommand();
String sqlAddNew = #"INSERT INTO Expenses (name, amount,receipt,details)
Values(#name,#amount,#receipt,#details)";
Cmd = new SqlCeCommand(sqlAddNew, con);
Cmd.Parameters.Add("#name", SqlDbType.NVarChar).Value = txtName.Text;
Cmd.Parameters.Add("#amount", SqlDbType.NVarChar).Value = txtAmount.Text;
Cmd.Parameters.AddWithValue("#receipt", SqlDbType.NVarChar).Value = txtRecept.Text;
Cmd.Parameters.AddWithValue("#details", SqlDbType.NVarChar).Value = txtDetails.Text;
Cmd.ExecuteNonQuery();
}
catch (Exception exception)
{
txtAmount.Text = exception.ToString();
}
finally
{
if (con.State == ConnectionState.Open) con.Close();
}
}
}
I am not getting why this error occurring.
Acadamy.sdf structure is as below:
I am able to retrieve data from another table of the same database. What will be the problem?
Whenever I get an error about a table that does not exist I use the SQL Server Management Studio and check if the table really is missing or if I just have a typo in my query.
Unfortunately the current version of the Management Studio no longer supports SQL Server Compact Database and you will have to use the 2008 version. You can get it directly from Microsoft: SQL Server 2008 R2 Management Studio Express
I have a problem using Visual Studio 2010. I am using a service-based database (.mdf).
I have created a table manually in Visual Studio with some information. The code I have written can read from the table but when I insert new information it looks like the data is added to some other database.
I can read information from the correct table but when I add information to the table I can’t see the changes in Server Explorer in Visual Studio.
I don't know why to different databases are used! Does anybody know the problem?
Here is my code:
public class DataAccess
{
private SqlConnection sqlConnection;
private SqlCommand sqlCommand;
private SqlDataAdapter dataAdapterAnimal;
private DataSet dataset;
private string connectionString = DBAccessLayer.Properties.Settings.Default.AnimalDBConnectionString;
public DataSet LoadAnimalDataSet()
{
dataset = new DataSet();
using (sqlConnection = new SqlConnection(connectionString))
{
sqlConnection.Open();
dataAdapterAnimal = new SqlDataAdapter("SELECT * FROM AnimalTable", sqlConnection);
dataAdapterAnimal.Fill(dataset, "AnimalTable");
sqlConnection.Close();
return dataset;
}
}
public void AddAnimal(int animalID, string name, double age, string category, string gender, string extraAnimalInfo)
{
sqlConnection = new SqlConnection(connectionString);
sqlCommand = new SqlCommand("INSERT INTO AnimalTable VALUES(#AnimalID, #Name, #Age, #Category, #Gender, #ExtraAnimalInfo)", sqlConnection);
try
{
sqlConnection.Open();
sqlCommand.Parameters.Add(new SqlParameter("#AnimalID", animalID));
sqlCommand.Parameters.Add(new SqlParameter("#Name", name));
sqlCommand.Parameters.Add(new SqlParameter("#Age", age));
sqlCommand.Parameters.Add(new SqlParameter("#Category", category));
sqlCommand.Parameters.Add(new SqlParameter("#Gender", gender));
sqlCommand.Parameters.Add(new SqlParameter("#ExtraAnimalInfo", extraAnimalInfo));
sqlCommand.ExecuteNonQuery();
sqlConnection.Close();
}
catch (Exception ex)
{
throw;
}
}
I haven't seen your connection string yet - but from your description, it seems it might be this problem here:
the whole User Instance and AttachDbFileName= approach is flawed - at best! When running your app in Visual Studio, it will be copying around the .mdf file (from your App_Data directory to the output directory - typically .\bin\debug - where you app runs) and most likely, your INSERT works just fine - but you're just looking at the wrong .mdf file in the end!
If you want to stick with this approach, then try putting a breakpoint on the myConnection.Close() call - and then inspect the .mdf file with SQL Server Mgmt Studio Express - I'm almost certain your data is there.
The real solution in my opinion would be to
install SQL Server Express (and you've already done that anyway)
install SQL Server Management Studio Express
create your database in SSMS Express, give it a logical name (e.g. MyDatabase)
connect to it using its logical database name (given when you create it on the server) - and don't mess around with physical database files and user instances. In that case, your connection string would be something like:
Data Source=.\\SQLEXPRESS;Database=MyDatabase;Integrated Security=True
and everything else is exactly the same as before...
I need to connect to a Oracle DB (external) through Visual Studio 2010. But I dont want to install Oracle on my machine.
In my project I referenced: System.Data.OracleClient. But its not fulfilling the need.
I have an "Oracle SQL Developer IDE" in which I run SQL queries against oracle db.
I have this code so far:
private static string GetConnectionString()
{
String connString = "host= serverName;database=myDatabase;uid=userName;pwd=passWord";
return connString;
}
private static void ConnectingToOracle()
{
string connectionString = GetConnectionString();
using (OracleConnection connection = new OracleConnection())
{
connection.ConnectionString = connectionString;
connection.Open();
Console.WriteLine("State: {0}", connection.State);
Console.WriteLine("ConnectionString: {0}",
connection.ConnectionString);
OracleCommand command = connection.CreateCommand();
string sql = "SELECT * FROM myTableName";
command.CommandText = sql;
OracleDataReader reader = command.ExecuteReader();
while (reader.Read())
{
string myField = (string)reader["MYFIELD"];
Console.WriteLine(myField);
}
}
}
So far I read these blogs:
http://st-curriculum.oracle.com/tutorial/DBXETutorial/index.htm
http://blogs.msdn.com/b/kaevans/archive/2009/07/18/connecting-to-oracle-from-visual-studio.aspx
So far I have not downloaded anything from Oracle. What steps should I take to make this happen?
First off you need to download and install ODP from this site
http://www.oracle.com/technetwork/topics/dotnet/index-085163.html
After installation add a reference of the assembly Oracle.DataAccess.dll.
Your are good to go after this.
using System;
using Oracle.DataAccess.Client;
class OraTest
{
OracleConnection con;
void Connect()
{
con = new OracleConnection();
con.ConnectionString = "User Id=<username>;Password=<password>;Data Source=<datasource>";
con.Open();
Console.WriteLine("Connected to Oracle" + con.ServerVersion);
}
void Close()
{
con.Close();
con.Dispose();
}
static void Main()
{
OraTest ot= new OraTest();
ot.Connect();
ot.Close();
}
}
You can use Oracle.ManagedDataAccess NuGet package too (.NET >= 4.0, database >= 10g Release 2).
Using Nuget
Right click Project, select Manage NuGet packages...
Select the Browse tab, search for Oracle and install Oracle.ManagedDataAccess
In code use the following command (Ctrl+. to automatically add the using directive).
Note the different DataSource string which in comparison to Java is
different.
// create connection
OracleConnection con = new OracleConnection();
// create connection string using builder
OracleConnectionStringBuilder ocsb = new OracleConnectionStringBuilder();
ocsb.Password = "autumn117";
ocsb.UserID = "john";
ocsb.DataSource = "database.url:port/databasename";
// connect
con.ConnectionString = ocsb.ConnectionString;
con.Open();
Console.WriteLine("Connection established (" + con.ServerVersion + ")");
The next approach work to me with Visual Studio 2013 Update 4
1- From Solution Explorer right click on References then select add references
2- Assemblies > Framework > System.Data.OracleClient > OK
and after that you free to add using System.Data.OracleClient in your application and deal with database like you do with Sql Server database except changing the prefix from Sql to Oracle as in SqlCommand become OracleCommand for example to link to Oracle XE
OracleConnection oraConnection = new OracleConnection(#"Data Source=XE; User ID=system; Password=*myPass*");
public void Open()
{
if (oraConnection.State != ConnectionState.Open)
{
oraConnection.Open();
}
}
public void Close()
{
if (oraConnection.State == ConnectionState.Open)
{
oraConnection.Close();
}}
and to execute some command like INSERT, UPDATE, or DELETE using stored procedure we can use the following method
public void ExecuteCMD(string storedProcedure, OracleParameter[] param)
{
OracleCommand oraCmd = new OracleCommand();
oraCmd,CommandType = CommandType.StoredProcedure;
oraCmd.CommandText = storedProcedure;
oraCmd.Connection = oraConnection;
if(param!=null)
{
oraCmd.Parameters.AddRange(param);
}
try
{
oraCmd.ExecuteNoneQuery();
}
catch (Exception)
{
MessageBox.Show("Sorry We've got Unknown Error","Connection Error",MessageBoxButtons.OK,MessageBoxIcon.Error);
}
}
Basically in this case, System.Data.OracleClient need access to some of the oracle dll which are not part of .Net. Solutions:
Install Oracle Client , and add bin location to Path environment varaible of windows
OR
Copy
oraociicus10.dll (Basic-Lite version) or aociei10.dll (Basic version),
oci.dll, orannzsbb10.dll and oraocci10.dll from oracle client installable folder to bin folder of application so that application is able to find required dll