I have a SQLite database with one table for cities name now I want to include this database to my monotouch project, connect to this database and select to this table. But I can find any tutorial to do this.
I don't new to create the database or create a new record. I just need to read the table.
Can anyone explain me how can I connect to my sqlite database an make a select.
Thanks in advance.
UPDATE
using(var connection = new SqliteConnection ("Data Source=zurfers.sqlite"))
{
using (var cmd = connection.CreateCommand()) {
connection.Open ();
cmd.CommandText = "SELECT * FROM City";
using (var reader = cmd.ExecuteReader()) {
while (reader.Read()) {
wordCollection = (string[])reader ["Name"];
}
}
}
}
include your DB file in your MonoTouch project and mark it as content.
using(var connection = new SqliteConnection ("Data Source=MyDatabase.sqlite"))
{
using (var cmd = connection.CreateCommand()) {
connection.Open ();
cmd.CommandText = "this is my query";
using (var reader = cmd.ExecuteReader()) {
while (reader.Read()) {
code = (string)reader ["ColumnName"];
}
}
}
}
Related
I'm using SQLCipher (community edition) running with .NET and Entity Core. Everything works perfectly including changing a password on existing database.
For example, if DB is protected with password '1' it is no issue to change (rekey) it to '2' or anything else. However, there is an issue when I want to protect unprotected database or remove protection from a database that has password.
At the moment the code that changes password for a DB looks like:
public bool Rekey(string oldKey, string newKey)
{
SqliteConnection conn = GetConnection(oldKey);
try
{
conn.Open();
using (var command = conn.CreateCommand())
{
command.CommandText = $"PRAGMA rekey = '{newKey}';";
int rowsChanged = command.ExecuteNonQuery();
}
conn.Close();
}
catch
{
return false;
}
return true;
}
private SqliteConnection GetConnection(string key)
{
SqliteConnection conn;
if (_dbaccessBytes == null)
{
conn = new SqliteConnection
{
ConnectionString = new SqliteConnectionStringBuilder()
{
DataSource = _databasePath,
Mode = SqliteOpenMode.ReadWriteCreate
}.ToString()
};
}
else
{
conn = new SqliteConnection
{
ConnectionString = new SqliteConnectionStringBuilder()
{
DataSource = _databasePath,
Mode = SqliteOpenMode.ReadWriteCreate,
Password = key
}.ToString()
};
}
return conn;
}
So when we don't have password protection and send oldKey as NULL and newKey as some value - it would just run, but will not set password. No errors.
I tried to look up solution, but no luck yet. May be I'm missing some understanding and setting and removing key should be done not like 'PRAGMA rekey', but in some other method?
Thanks in advance.
'PRAGMA rekey' is used to change existing password for the database. To set password for unencrypted database or remove it from a password protected one should use sqlcipher_export() function.
This is described in SQLCipher documentation here.
And maybe someone would find code sample useful. For decrypting db you should just establish connection like:
SqliteConnection conn = GetConnection();
conn.Open();
using var command = conn.CreateCommand();
command.CommandText = $"ATTACH DATABASE '{newDBPath}' AS plaintext KEY '';";
command.ExecuteNonQuery();
command.CommandText = #"SELECT sqlcipher_export('plaintext');";
command.ExecuteNonQuery();
command.CommandText = #"DETACH DATABASE plaintext;";
command.ExecuteNonQuery();
Consequently, for encrypting you should do the similarly:
SqliteConnection conn = GetConnection();
conn.Open();
using var command = conn.CreateCommand();
command.CommandText = $"ATTACH DATABASE '{newDBPath}' AS encrypted KEY '{newKey}';";
command.ExecuteNonQuery();
command.CommandText = #"SELECT sqlcipher_export('encrypted');";
command.ExecuteNonQuery();
command.CommandText = #"DETACH DATABASE encrypted;";
command.ExecuteNonQuery();
I'm Using .NET Core 2.1.2.
I use SQL Database for DB and run the following code, the second sqlbulk.WriteToServer raises "Unexpected existing transaction" exception.
using System;
using System.Data;
using System.Data.SqlClient;
using System.Transactions;
namespace sqldb
{
class Program
{
static void Main(string[] args)
{
var constr = new SqlConnectionStringBuilder(){
DataSource = "xxxxxxxx.database.windows.net",
UserID = "xxxxxxx",
Password = "xxxxxx"
};
using (var scope = new TransactionScope()){
constr.InitialCatalog = "DB1";
var dtable = new System.Data.DataTable();
dtable.TableName = "T1";
dtable.Columns.Add("C1");
var drow = dtable.NewRow();
drow["C1"] = 1;
dtable.Rows.Add(drow);
using (var con = new SqlConnection(constr.ToString())){
con.Open();
var sqlbulk = new System.Data.SqlClient.SqlBulkCopy(con);
sqlbulk.DestinationTableName = "T1";
sqlbulk.WriteToServer(dtable);
}
constr.InitialCatalog = "DB2";
using (var con = new SqlConnection(constr.ToString())){
con.Open();
var sqlbulk = new System.Data.SqlClient.SqlBulkCopy(con);
sqlbulk.DestinationTableName = "T1";
sqlbulk.WriteToServer(dtable);
}
scope.Complete();
}
}
}
}
I executed the following query on each DB and confirmed the status of Elastic Transaction, it was registered as DTC.
SELECT * FROM sys.dm_tran_active_transactions
In Transaction Scope, inserting data with sqlbulkcopy to multiple DBs of SQL Database seems to cause an error, but is there some workaround?
(In the Transaction Scope, inserting data with multiple SqlBulkCopy for the same db / simple insert for multiple db is working fine)
Looks like SqlBulkCopy gets confused with System.Transactions. With your SqlConnection already enlisted in the System.Transactions.Transaction, you can start a "nested" transaction with the SqlConnection.BeginTransaction, and pass that transaction to SqlBulkCopy. EG
using (var con = new SqlConnection(constr.ToString()))
{
con.Open();
using (var tran = con.BeginTransaction())
{
var options = new SqlBulkCopyOptions();
var sqlbulk = new SqlBulkCopy(con,options,tran);
sqlbulk.DestinationTableName = "T1";
sqlbulk.WriteToServer(dtable);
tran.Commit();
}
}
Hi can you help me with this??
I have this code and i want to display the result of my query into my 3rd Textbox but it not displaying.
string query = "SELECT UserID FROM [IBSI].[sec].[Users] WHERE UserName = '" + TextBox2.Text + "'";
if (query != null)
{
using (SqlConnection conn = new SqlConnection(connect))
{
using (SqlCommand cmd = new SqlCommand(query, conn))
{
conn.Open();
SqlDataReader rdr = cmd.ExecuteReader();
if (rdr.HasRows)
{
while (rdr.Read())
{
TextBox3.Text=rdr["UserID"].ToString() ;
}
}
}
}
}
But then i just use this query without the where condition i can see the output;
string query = "SELECT UserID FROM [IBSI].[sec].[Users]";
Thanks in advance
I'd recommend using parameterized queries for this task. Also, generating sql code from user input (like text boxes/memos) is prone to sql injections (user may enter any sql code into the textbox that may damage database data), so it'd be great to validate input data.
Sample parameter usage is like this:
string query = "SELECT UserID FROM [IBSI].[sec].[Users] WHERE UserName = #1";
if (query != null)
{
using (SqlConnection conn = new SqlConnection(connect))
{
using (SqlCommand cmd = new SqlCommand(query, conn))
{
SqlParameter p1 = new SqlParameter("#1", TextBox2.Text);
cmd.Parameters.Add(p1);
conn.Open();
SqlDataReader rdr = cmd.ExecuteReader();
if (rdr.HasRows)
{
while (rdr.Read())
{
TextBox3.Text=rdr["UserID"].ToString() ;
}
}
}
}
}
Step through the debugger and verify that your query is returning results.
ey Bert change in your code as follows:
string query = "SELECT UserID FROM [IBSI].[sec].[Users] WHERE UserName= '"+TextBox2.Text+ "'";
if (query != null)
{
using (SqlConnection conn = new SqlConnection(connect))
{
using (SqlCommand cmd = new SqlCommand(query, conn))
{
conn.Open();
int UserId;
UserId=Convert.ToInt32(cmd.ExecuteScalar());
TextBox3.Text=UserId.ToString() ;
}
}
}
How can I point my ASP.NET MVC application to a MySQL database?
Once you download the MySQL ADO.NET Connector it's a simple matter of referencing the assembly in your project and writing the queries, the same way you would do in any other application, nothing specific MVC:
using (var connection = new MySqlConnection(ConnectionString))
using (var cmd = connection.CreateCommand())
{
connection.Open();
cmd.CommandText = "SELECT name FROM foo;";
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
string name = reader.GetString(reader.GetOrdinal("name"));
// TODO: do something with the name ...
}
}
}
I'm new to windows mobile programming and I'm trying to create a Windows Mobile 6 application using sqlite. Write now I have built a dummy test application where I try to read the contents of a an sqlite table.
The problem is that I keep receiving SQLiteException: Unable to open the database file.
My code is below:
using (var cn = new SQLiteConnection(#"Data Source=C:myfirsttest.s3db;"))
{
try
{
//Connect to SQLite database
cn.Open();
//Create the SQL Command
var cmd = new SQLiteCommand();
cmd.Connection = cn;
cmd.CommandText = "SELECT * FROM MyTable";
//Retrieve the records using SQLiteDataReader
var dr = cmd.ExecuteReader();
while (dr.Read())
{
//display records
var id = dr["ID"].ToString();
}
}
catch(Exception ex)
{
//display any exeptions
var except = ex.Message;
}
finally
{
cn.Close();
}
}
Can anyone help me please with that? Or suggest a tutorial where I can find how to setup sqlite in a windows mobile 6 project?
Windows CE (the base OS for WinMo) does not have drives nor does it have a concept of a working folder. This means that all paths must be fully qualified. You probably want something like:
new SQLiteConnection(#"Data Source=\myfirsttest.s3db;")
or
new SQLiteConnection(#"Data Source=\[my app path]\myfirsttest.s3db;")