Sqlite for .net can't add column using alter table - c#

SQL script is:
ALTER TABLE SYNC_INFO
ADD COLUMN DB_VERSION INTEGER;
UPDATE SYNC_INFO
SET DB_VERSION = 1
WHERE ID = 0;
C# code is:
using (DbConnection con = new SQLiteConnection("Data Source=" + Filename + ";Version=3"))
{
con.Open();
using (DbCommand command = con.CreateCommand())
{
command.CommandText = script;
command.ExecuteNonQuery();
}
}
The problem is sqlite says "database is locked" while trying to evaluate the ALTER TABLE command. All over operations like read/write rows are successful.
Another one - Mozilla's SQLite manager successfully evaluating this script.
Is it possible problem in .net wrapper of SQLite?

You can get the error message "database is locked" only when some other connection has an active transaction.
That transaction might be from some forgotten connection in your program, or in some other program accessing the database.

Related

Can not retrieve a list of tables from an Oracle database - conn.GetSchema("Tables")

I need to retrieve the list the tables in an Oracle database that is defined by a DSN that is using the Oracle ODBC driver.
However, OdbcConnection.GetSchema("Tables") throws an exception ERROR [HYT00] [Oracle][ODBC][Ora]ORA-01013: user requested cancel of current operation\n or ORA-00604: error occurred at recursive SQL level 1 after about 30 seconds.
using (OdbcConnection connection = new OdbcConnection("Driver={Oracle in OraDB18Home1};Dbq=XE;Uid=system;Pwd=mypassword;"))
{
connection.Open();
//Also unsuccessful with "Views" and "Columns", but works with "DataTypes" and "Restrictions"
DataTable schema = connection.GetSchema("Tables");
}
The database is newly installed and is not too big.
I can call GetSchema() without parameters to successfully retrieve all supported schema collections.
I can also successfully run a query against my database:
OdbcCommand command = new OdbcCommand("SELECT * FROM vendors")
{
Connection = connection
};
OdbcDataReader reader = command.ExecuteReader();
You should stop using ODBC. Use ODP.NET - this is gold standard Oracle .NET provider. And use "Managed" version, i.e. Oracle.ManangedDataAccess. This code below will work fine
var conn = new OracleConnection("Data Source=server:1521/sid;password=pwd;user id=usr");
conn.Open();
var tbl = conn.GetSchema();
conn.Close();
Consile.WriteLine(tbl.Rows.Count.ToString());

How to connect SQLite with my C# application

i have a problem with making a local database into my c# project and creating it..
I tried first with making a Microsoft Sql Server but the problem is that i need to make app which should run on every pc. The app should input data from user , and collect it to the database, and on every start of program, the database should be filled with the leftover of earlier input.. What you suggest me to do?
First to connect your c# application with sqlite you should start with getting connection string
private static string executableLocation = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
private static string oldconnectionstring = Path.Combine(executableLocation, "YourDB.db");
private static string connectionString = "Data Source =" + oldconnectionstring.ToString();
After getting connection, to add your input to database follow below steps
using (SQLiteConnection conn = new SQLiteConnection(connectionString))
{
//Open connection to DB
conn.Open();
//Query to be fired
string sql = "Your Query to insert rows";
//Executing the query
using (SQLiteCommand cmd = new SQLiteCommand(sql, conn))
{
//Executing the query
cmd.CommandText = sql;
cmd.ExecuteNonQuery();
}
//Close connection to DB
conn.Close();
}

System.InvalidOperationException: Cannot perform CAS Asserts in Security Transparent methods

I have a SQL CLR trigger written in C# 4.0 and deployed on SQL Server 2014. Whenever an insertion happens in a table in SQL Server, this CLR trigger's job is to import that row in an Oracle database. So basically I have to import data in Oracle database whenever an insert query is fired on a table in SQL Server 2014. This is my first CLR SQL trigger project and below is what I am doing:
[SecurityCritical]
[OraclePermission(System.Security.Permissions.SecurityAction.Assert, Unrestricted = true)]
[SqlTrigger(Name = "FetchSurvey", Target = "temp", Event = "FOR INSERT")]
public static void FetchSurvey()
{
SqlTriggerContext triggerContext = SqlContext.TriggerContext;
// Create result set to store data
DataSet resultSet = new DataSet();
// Create a new SQL command
using (SqlCommand command = new SqlCommand("SELECT * FROM INSERTED"))
{
// Create a new SQL connection
using (command.Connection = new SqlConnection("context connection=true"))
{
// Connect to the database
command.Connection.Open();
// Execute procedure
using (SqlDataAdapter adapter = new SqlDataAdapter(command))
{
adapter.Fill(resultSet);
}
// Disconnect from the database
command.Connection.Close();
}
}
SqlPipe sqlP = SqlContext.Pipe;
// Return data
if (resultSet.Tables.Count > 0)
SaveSurvey(resultSet);
sqlP.Send("Finaly its done!!");
}
public static void SaveSurvey(DataSet dsSurvey)
{
using (OracleConnection con = new OracleConnection("my oracle connection string"))
{
if (con.State == ConnectionState.Closed)
con.Open();
DataRowView drv = dsSurvey.Tables[0].DefaultView[0];
using (OracleCommand cmd = new OracleCommand("AddMetaData", con))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("V_id", drv["TemplateID"]);
cmd.Parameters.AddWithValue("V_Title", drv["TemplateName"]);
cmd.Parameters.AddWithValue("V_CreatedBy", drv["CreatedBy"]);
cmd.Parameters.AddWithValue("V_IsActive", drv["IsActive"]);
cmd.ExecuteNonQuery();
}
}
}
And this is my code to create assembly/deploy trigger:
CREATE ASSEMBLY TriggerImportSurvey
FROM 'C:\ImportSurvey\SQL-CLR-Trigger.dll'
With Permission_Set = External_Access;
Now the problem is whenever I run an insert query in SQL Server to insert data, I got below error in SQL Server:
Msg 6522, Level 16, State 1, Procedure tri_InsertSurvey_clr, Line 18
A .NET Framework error occurred during execution of user-defined routine or aggregate "tri_InsertSurvey_clr":
System.InvalidOperationException: Cannot perform CAS Asserts in Security Transparent methods
System.InvalidOperationException:
at Triggers.FetchSurvey()
tri_InsertSurvey_clr is the trigger which is responsible for executing the assembly whenever I run an insert statement.
Please tell me what I am missing so that I am getting this error, Also if there a more elegant way of implementing a CLR SQL trigger then please also suggest that.
NOTE: When I tried to save the data using a trigger in SQL Server I was successful, but now when I am trying to save it in Oracle database, I am getting this error. Also the Oracle database is installed on another machine.

Programmatically create sqlite db if it doesn't exist?

I am trying to create an sqlite db programmatically if it doesn't exist. I have written the following code but I am getting an exception at the last line.
if (!System.IO.File.Exists("C:\\Users\\abc\\Desktop\\1\\synccc.sqlite"))
{
Console.WriteLine("Just entered to create Sync DB");
SQLiteConnection.CreateFile("C:\\Users\\abc\\Desktop\\1\\synccc.sqlite");
string sql = "create table highscores (name varchar(20), score int)";
SQLiteCommand command = new SQLiteCommand(sql, sqlite2);
command.ExecuteNonQuery();
}
sqlite2 = new SQLiteConnection("Data Source=C:\\Users\\abc\\Desktop\\1\\synccc.sqlite");
I get the exception at the line command.ExecuteNonQuery(); The exception is Invalid operation exception was unhandled. Is there any other way to add an sqlite file to your project? Can I do it manually? If not then how can I solve the above issue?
To execute any kind of data definition command on the database you need an open connection to pass the command. In your code you create the connection AFTER the execution of the query.
Of course, after that creation, you need to open the connection
if (!System.IO.File.Exists(#"C:\Users\abc\Desktop\1\synccc.sqlite"))
{
Console.WriteLine("Just entered to create Sync DB");
SQLiteConnection.CreateFile(#"C:\Users\abc\Desktop\1\synccc.sqlite");
using(var sqlite2 = new SQLiteConnection(#"Data Source=C:\Users\abc\Desktop\1\synccc.sqlite"))
{
sqlite2.Open();
string sql = "create table highscores (name varchar(20), score int)";
SQLiteCommand command = new SQLiteCommand(sql, sqlite2);
command.ExecuteNonQuery();
}
}
However, if you use the version 3 of the provider, you don't have to check for the existence of the file. Just opening the connection will create the file if it doesn't exists.

Create an SQL Express 2008 database in C# code, but login fails when trying to connect with a sysadmin

I have a piece of code that creates an SQL Server Express 2008 in runtime, and then tries to connect to it to execute a database initialization script in Transact-SQL. The code that creates the database is the following:
private void CreateDatabase()
{
using (var connection = new SqlConnection(
"Data Source=.\\sqlexpress;Initial Catalog=master;" +
"Integrated Security=true;User Instance=True;"))
{
connection.Open();
using (var command = connection.CreateCommand())
{
command.CommandText =
"CREATE DATABASE " + m_databaseFilename +
" ON PRIMARY (NAME=" + m_databaseFilename +
", FILENAME='" + this.m_basePath + m_databaseFilename + ".mdf')";
command.ExecuteNonQuery();
}
}
}
The database is created successfully. After that, I try to connect to the database to run the initialization script, by using the following code:
private void ExecuteQueryFromFile(string filename)
{
string queryContent = File.ReadAllText(m_filePath + filename);
this.m_connectionString = string.Format(
#"Server=.\SQLExpress; Integrated Security=true;Initial Catalog={0};", m_databaseFilename);
using (var connection = new SqlConnection(m_connectionString))
{
connection.Open();
using (var command = connection.CreateCommand())
{
command.CommandText = queryContent;
command.CommandTimeout = 0;
command.ExecuteNonQuery();
}
}
}
However, the connection.Open() statement fails, throwing the following exception:
Cannot open database "TestData"
requested by the login. The login
failed. Login failed for user
'MYDOMAIN\myusername'.
I am completely puzzled by this error because the account I am trying to connect with has sysadmin privileges, which should allow me to connect any database (notice that I use a connection to the master database to create the database in the first place).
Is there a reason you specify User Instance=True when you create it but not when you try to connect to it?
When you create it after connecting with User Instance, it will create the database files but does not attach it to your actual instance. You'll either have to not specify User Instance=True in the first connection string or add it to the second and specify the database file to use.
Is the user you are logging with have rights to the database 'TestData'?
If not grant the user the privileges required.
I am not sure if this means anything, but in your first create you are connecting to server
.\\sqlexpress
The second one is
.\SQLExpress
You'll need to issue a CREATE USER command (see: http://msdn.microsoft.com/en-us/library/ms173463.aspx) after creating the database but before trying to open a connction to that database.
For example:
CREATE USER 'MYDOMAIN\myusername' FOR LOGIN 'MYDOMAIN\myusername'

Categories