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.
Related
Today I tried to use SQLite database with my small WPF application, but I keep getting XamlParseException was unhandled. By taking out lines of code, I managed to notice that cmd.ExecuteNonQuery();causes the exception. In the rest, the SQLite connection seems working and also creating the database file.
public MainWindow()
{
InitializeComponent();
SQLiteConnection conn = new SQLiteConnection(#"Data Source=C:\Users\Vitas\Desktop\TimeCounter.sqlite");
conn.Open();
string commandText = "CREATE TABLE [EmpInfo]";
SQLiteCommand cmd = new SQLiteCommand(commandText, conn);
cmd.ExecuteNonQuery();
conn.Close();
}
You need a definition of fields when creating the table. Example:
string commandText = "CREATE TABLE [EmpInfo] (EmpId int)";
Ref: Create table syntax
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.
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.
This is my code for inserting into database from textfields.
SqlConnection Connection = new SqlConnection("Data Source=ESHA\\SQLEXPRESS;Initial Catalog=Gen_Lic;User ID=sa;Password=sa#");
SqlCommand Command = Connection.CreateCommand();
try
{
// Open Connection
Connection.Open();
////Console.WriteLine("Connection Opened");
// Create INSERT statement with named parameters
Command.CommandText = "INSERT INTO Gen_Lic(Lic_No, UserID, Org, UserName, SolType, Version, Lic_Type, Meap_Supp, Lic_From, Lic_To, Supp_From, Supp_To, Max_User, Max_Mach, Mach_IP, Mach_MAC) VALUES (#Lic_No, #UserID, #Org, #UserName, #SolType, #Version, #Lic_Type, #Meap_Supp, #Lic_From, #Lic_To, #Supp_From, #Supp_To, #Max_User, #Max_Mach, #Mach_IP, #Mach_MAC)";
// Add Parameters to Command Parameters collection
Command.Parameters.AddWithValue("#Lic_No", txtLNo.Text);
Command.Parameters.AddWithValue("#UserID", txtUID.Text);
Command.Parameters.AddWithValue("#Org", txtOrg.Text);
Command.Parameters.AddWithValue("#UserName", txtUName.Text);
Command.Parameters.AddWithValue("#SolType", txtSType.Text);
Command.Parameters.AddWithValue("#Version", txtVer.Text);
Command.Parameters.AddWithValue("#Lic_Type", drpLType.SelectedItem.Text);
Command.Parameters.AddWithValue("#Meap_Supp", rdoMeapSupport.SelectedValue.ToString());
Command.Parameters.AddWithValue("#Lic_From", lblLFrom.Text);
Command.Parameters.AddWithValue("#Lic_To", lblLTo.Text);
Command.Parameters.AddWithValue("#Supp_From", lblSuppFrom.Text);
Command.Parameters.AddWithValue("#Supp_To", lblSuppTo.Text);
Command.Parameters.AddWithValue("#Max_User", txtMaxUsr.Text);
Command.Parameters.AddWithValue("#Max_Mach", txtMaxMach.Text);
Command.Parameters.AddWithValue("#Mach_IP", txtMachIP.Text);
Command.Parameters.AddWithValue("#Mach_MAC", txtMachMac.Text);
Connection.Close();
}
Now the problem is the code is working fine, but the values are not getting inserted into the database. Also, when I apply a breakpoint at the starting of the connection formation, a new blank IE window opens up.
Can someone guide me where am I going wrong?
I think, you are missing the following:
Command.ExecuteNonQuery();
before the Connection.Close()
Please run this query again the database
Command.ExecuteNonQuery();
before closing the connection
I am attempting to insert data into a local SQLITE database file from a C# application. The transaction does not throw any errors but the data is not inserted. The same insert statement works from within a query analyzer.
Do I need to perform a commit? Is there a Commit method?
Command's transaction property is null..
var command = new SQLiteCommand(insert.BuildInsert(tableName,keyValuePairs),Connection);
command.ExecuteNonQuery();
UPDATE:
I have also tried to assciate my SQLiteCommand with a SQLiteTransaction but have had no luck.
try
{
SQLiteTransaction liteTransaction = Connection.BeginTransaction();
SQLiteCommand command = new SQLiteCommand(insert.BuildInsert(tableName, keyValuePairs), Connection);
command.Transaction = liteTransaction;
command.ExecuteNonQuery();
liteTransaction.Commit();
}
catch (SQLiteException e)
{
//error
connection.Close();
}
The BuildInsert method just constructs a string that is the INSERT. The insert works fine in a query analyzer.
public string BuildInsert(string tableName, IDictionary<string, string> testDataDic)
{
stringBuilder = new StringBuilder(String.Format("INSERT INTO {0} ", tableName));
AddColumns(stringBuilder,testDataDic.Keys);
AddValues(stringBuilder, testDataDic.Values);
return stringBuilder.ToString();
}
This is an example of the INSERT statement. This works fine outside of the code but does not throw any errors:
INSERT INTO TestData (walking,running,image,yoga,exercise,meditation,hobby,somethingelse,howoften,numtechniques,userreturn,chosentechnique,chosentechnique)VALUES ("true","I will try to use deep breathing.","false","true","false","false","true","true","When I'm stressed","1","true","deepbreathing","deepbreathing"); COMMIT;
DOH! So the local database build operation was set to 'Always copu' I have multiple versions of the same file.
Sorry for that. That's lame.