Unhandled Exception: C# Sqlite - c#

I just started to use SQLite. Doesn't seem to look like MySQL and SQL Server and MS Access that I use. I sought for several information online, nothing I could really find as well I decided to post here.
It connects well, and the libraries are present in the folder, but when I try to insert into the database, it throws an exception to the console.
My code looks like this
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Data.SQLite;
namespace sqliteInsert
{
class Program
{
static void Main(string[] args)
{
string constring = "Data Source=C:\\Users\\DornellPC\\Desktop\\people_db.db;Version=3;New=False;Compress=True;";
using (SQLiteConnection con = new SQLiteConnection(constring))
{
try
{
string sql = "insert into people_data (first_name,last_name,tel,email) values ('Jack','Darwin','0966358936','j_darwin#fsmail.net')";
con.Open();
Console.WriteLine("Connection open!");
using (SQLiteCommand cmd = new SQLiteCommand(sql,con))
{
cmd.ExecuteNonQuery();
Console.WriteLine("Success!");
Console.ReadLine();
}
}
catch(Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
}
}
}
and no information has been inserted into the database as it throws this exception:
Unhandled Exception: System.IO.FileNotFoundException: Could not load file or ass embly 'System.Data.SQLite, Version=1.0.105.2, Culture=neutral, PublicKeyToken=db 937bc2d44ff139' or one of its dependencies. The system cannot find the file specified.
at sqliteInsert.Program.Main(String[] args)

Related

csharp mysql compile error CS0246 under powershell

I am attempting to compile a simple C# program to do a select on one of the tables in the MySQL database on my windows 10 laptop. When I attempt to compile the code under Developer PowerShell for VS 2019 using the following command:
csc mysql1.cs
I get the error message error CS0246: The type or namespace name 'MySql' could not be found
I checked under the directory C:\Program Files (x86)\MySQL\MySQL Connector Net 8.0.18\Assemblies\v4.5.2 and I did indeed have the file MySql.Data.dll
All the articles I found with google stated that I had to "add a reference" to my project. I do not have a project, this is just a command line compile.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MySql.Data.MySqlClient;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("This is a MySQL Test");
string mysql_info = "Persist Security Info=False;server=localhost;database=myschema;uid=root;password=mypassword";
MySql.Data.MySqlClient.MySqlConnection dbConn =
new MySql.Data.MySqlClient.MySqlConnection(mysql_info);
MySqlCommand cmd = dbConn.CreateCommand();
cmd.CommandText = "SELECT user_id from hockey_users WHERE username ='someone'";
try
{
dbConn.Open();
} catch (Exception erro) {
MessageBox.Show("Error" + erro);
this.Close();
}
MySqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
idnumber = reader.ToString();
Console.WriteLine("id = " + idnumber);
}
}
}
}

.NET Framework 4.5 Security: SSRS calls assembly in C# generating error

I have a SSRS report that references a dll assembly with one class that should call a stored procedure but returns this error.
Request for the permission of type 'System.Data.SqlClient.SqlClientPermission, system.Data, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed.
I don't know C# but have been limping through this with the help of some friends and colleagues. One had me add:
using System.Security.Permissions;
SqlClientPermission oPerm = new SqlClientPermission(PermissionState.Unrestricted);
oPerm.Assert();
to the class and I got this error:
Cannot perform CAS Asserts in Security Transparent methods
Leading me to look at what changed after .NET 4.0. I removed the SQLClientPermissions bit and added this to the AssemblyInfo:
[assembly: SecurityRules(SecurityRuleSet.Level2)]
[assembly: SecurityCritical()]
Which returned the original error. This is the Class:
using System.Text;
using System.Threading.Tasks;
using System.Data;
using System.Data.SqlClient;
using System.Security;
using System.Security.Permissions;
namespace ClassLibrary1
{
public class Class1
{
public static string logReportAttributes(string ReportName, int GlobalsTotalPages)
{
string retValue = String.Empty;
try
{
long TOCExecutionID = long.Parse(DateTime.Now.ToString("yyyyMMddHHmmss"));
SqlConnection connection = new SqlConnection("Persist Security Info=True;Trusted_Connection=True;initial catalog=InternalApps;data source=DEVSQL1;User ID=xxxxx;password=xxxxx;MultipleActiveResultSets=true;");
using (SqlCommand cmd = new SqlCommand("usp_LogReportAttributes", connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#ReportName", ReportName);
cmd.Parameters.AddWithValue("#GlobalsTotalPages", GlobalsTotalPages);
connection.Open();
cmd.ExecuteNonQuery();
}
if (connection.State == ConnectionState.Open || connection.State == ConnectionState.Broken)
{
connection.Close();
}
retValue = "Sent Successfully";
}
catch (Exception ex)
{
retValue = string.Format ( "{0} \n\r {1}" , ex.Message != null ? ex.Message : "" , ex.InnerException != null ? ex.InnerException.Message : "");
}
return retValue;
}
}
}
Does anyone have any idea what I'm doing wrong and how to get the correct security set up for this? Thank you!
The original error is an error that comes from code policy settings for the report server. There's a config file called RSSrvPolicy.config where you can specify different CodeGroups and their appropriate trust level (in ReportServer\bin). There you can grant a DLL FullTrust access.
This MSDN page goes over some of the details and more importantly has an example of a CodeGroup tag: https://msdn.microsoft.com/en-us/library/ms154658.aspx#Anchor_1

System.Data.OleDb.OleDbException' occurred in System.Data.dll

Hey Members i am new to C# Language and Visual Studio Platform recently i am learning how to connect access Database with visual Studio and first time with same code i have connected with database but after some time when i compiled again then there is error given in Title.
why this is happening ?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.OleDb;
namespace Clinic_Management_System
{
public partial class Login : Form
{
public Login()
{
InitializeComponent();
}
private void Login_Load(object sender, EventArgs e)
{
try
{
OleDbConnection connection = new OleDbConnection();
connection.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users
\Hassan Gillani\Documents\Clinic Management System.accdb; Persist Security Info = False; ";
connection.Open();
label1.Text = "Connected to Clinic Management System Database";
connection.Close();
}
catch (Exception exp)
{
MessageBox.Show("Error " + exp);
}
}
}
}
please visit given like to view screen short
http://s33.postimg.org/5ltm4dtnj/Error.png
Using the verbatim character (#) and splitting your path in the middle in not a good idea.
Spaces counts in paths so the filename used for your connection is
C:\Users \Hassan Gillani\Documents\Clinic Management System.accdb;
If you try to use File.Exists on this string you get false as result.
Do not split your connection string in the middle of the path
connection.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;
Data Source=C:\Users\Hassan Gillani\Documents\Clinic Management System.accdb;
Persist Security Info = False; ";

Issue with C# reading table on SQL Anywhere DB

using System;
using System.Data.OleDb;
using System.Diagnostics;
namespace PullData
{
class Program
{
static void Main(string[] args)
{
OleDbConnection connLocal = new OleDbConnection("Provider=SAOLEDB.10;Data Source=dental;Persist Security Info=True;User ID=dba;PWD=sql;Location=1.2.3.4");
OleDbCommand cmdLocal = new OleDbCommand("SELECT tran_num, amount, tran_date FROM transactions", connLocal);
try
{
connLocal.Open();
}catch (Exception connerr) { Debug.WriteLine(connerr.Message);}
OleDbDataReader readLocal = cmdLocal.ExecuteReader();
while (readLocal.Read())
{
Console.WriteLine(readLocal.GetString(0), readLocal.GetString(1), readLocal.GetString(2));
}
readLocal.Close();
connLocal.Close();
if (Debugger.IsAttached)
{
Console.ReadLine();
}
}
Above is the code I am attempting to run in Visual Studio 2015, I'm trying to connect to an old SQL Anywhere 10 DB, the connection string is directly from VS2015's Database Explorer that is connected and viewing tables (with the exception of my adding the PWD). This is just a stepping stone to view the table contents so I can later have the query written to a CSV or text.
The error I'm receiving when attempting to debug/run is:
An unhandled exception of type 'System.InvalidCastException' occurred in System.Data.dll
Additional information: Specified cast is not valid.
Which points to:
Console.WriteLine(readLocal.GetString(0), readLocal.GetString(1), readLocal.GetString(2));
Seems like it's not recognizing the reader. Anyone have any advice? Thanks!

Executing SQL Command in C# (Sql Exception Was Unhandled)

I am currently trying to connect to a database made in MS SQL Server and insert a row when a button on a form is clicked. Below is my code and an explanation of what is going wrong.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace WindowsFormsApplication10
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
SqlConnection myConnection = new SqlConnection("Data Source = (LocalDB)\\MSSQLLocalDB; AttachDbFilename = 'u:\\my documents\\visual studio 2015\\Projects\\WindowsFormsApplication10\\WindowsFormsApplication10\\InventoryDB.mdf'; Integrated Security = True; Connect Timeout = 30");
SqlCommand myCommand = new SqlCommand("INSERT INTO Table (Barcode, Item, Quantity) Values (123, 'Item 123', 5)", myConnection);
myConnection.Open();
myCommand.ExecuteNonQuery();
myConnection.Close();
}
}
}
I believe I have connected to the database, because in previous attempts I was getting an error at myConnection.Open(). Now I am getting an error at myCommand.ExecuteNonQuery(); which says:
SqlException was Unhandled: An Unhandled Exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll
Additional information: Incorrect syntax near the keyword 'Table'.
You can't use Table as the name for your table without qualifying it, since it's a SQL reserved word. Use [Table] instead if that is really your table name.
INSERT INTO [Table] (Barcode, Item, Quantity)...
Better yet, change the name of your table. Unless this is a copy/paste fail.

Categories