Sqlite database is accessible even with a wrong password - c#

In the following code for a C#.Net windows/desktop application, I have given wrong password while connecting to database but message box still displays Open.
SQLiteConnection conn = new SQLiteConnection("Data Source=DMB.sqlite;Version=3;");
conn.SetPassword("password");
conn.Open();
conn.Close();
conn = new SQLiteConnection("Data Source=DMB.sqlite;Version=3;Password=cdssss;");
conn.Open();
MessageBox.Show(conn.State.ToString());
Why it is still open when password is wrong?

This behavior is by design in the .net sqlite driver:
This is by design. The error message only occurs when you try to read from -OR-
write to the underlying database file. Opening the database does not typically
perform either operation.
It is recommended that you execute a SELECT statement on some well-known table
(e.g. "sqlite_master") immediately after opening the database in order to
determine if it is in a usable state.
Cited from Ticket 3eb097e917a7740f3499aae66e9a3cd021e9f81c:
https://system.data.sqlite.org/index.html/tktview/3eb097e917a7740f3499

Related

OLEDB commands aren't being saved in access database

I'm working in Windows Forms and trying to use OLEDB to connect to an access .accdb file.
I can SELECT data without issue.
I can execute Insert and Create commands with no error.
But when I check the database afterward the data is not showing.
For example, when I create a new Table, the code will say the table was created and if I try to create the table again without closing the Windows Form it will throw an error saying the table already exists, but if I close and restart the program it will let me create the table once more.
Also, if I look into the Access file I wont see the table.
I've tried multiple tests both with Access open and closed. The Connection String is correct as I have made changes to tables in the Access file and they are reflected in the SELECT queries I've sent.
I suspect there must be a setting in Access I must enable for it to autocommit changes. But I haven't found it.
OleDbConnection conn = new OleDbConnection(#"Provider = Microsoft.ACE.OLEDB.12.0; Data Source =Database2.accdb");
string query = "INSERT INTO [TestTable] ([Test_Name], [Test_Number]) VALUES (?, ?)";
try
{
OleDbCommand cmd = new OleDbCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = query;
cmd.Parameters.AddWithValue("Test_Name", list_all_meters[0][0].Name);
cmd.Parameters.AddWithValue("Test_Number", list_all_meters[0][0].Value);
cmd.Connection = conn;
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
MessageBox.Show("An Item has been successfully added", "Caption", MessageBoxButtons.OKCancel, MessageBoxIcon.Information);
}catch(Exception ex)
{
Debug.WriteLine(ex.Message);
}
Looks like the issue was I had set the Database "Copy to Output Directory" to Copy Always, which overwrote my changes every time I ran the program. Changing it to Copy if Newer fixed the issue.

SQLite connection string: 'Version' keyword is not supported in C#

I have a c# winform project that supposes to save data to SQLite database, I've already used the dll properly and it runs without error, but I get an exception when trigger the method with buttonClick event
here the exception i got : Keyword not supported :'version'.
this the connection string:
"Data Source = Diary.db;Version = 3;New = False;Compress = True;";
and this the complete method :
private void AddToDbaseSQL3()
{
try{
string query = "insert into Diary(title,date,mood,wheater,content)
values('"+TitleTextbox.Text+"','"
+dateTimePicker.Value.Date.ToString("yyyy-MM-dd HH:mm")+"','"
+MoodCombobox.SelectedItem+"','"
+WheaterCombobox.SelectedItem+"','"
+ContentTextbox.Text+"');";;
SqlConnection connect2 = new SqlConnection(connection2);
SqlCommand cmd = new SqlCommand(query,connect2);
SqlDataReader read;
connect2.Open();
read = cmd.ExecuteReader();
while(read.Read())
{
}
MessageBox.Show("created");
TitleTextbox.Text = "Title";
TitleTextbox.ForeColor = SystemColors.ControlLight;
ContentTextbox.Clear();
connect2.Close();
}catch(Exception e){
MessageBox.Show(e.Message);
}
}
I've looked to this link:
Keyword not supported: 'version'
and it said to change SqlConnection to SQLiteConnection but it ended with an error, can you tell what's is the right connection string ? or there is something wrong from my code/method? please tell me, thank you, I'm sorry because it's my first time using the SQLite
SqlConnection from System.Data.SqlClient is for SQL Server.
You need an dedicated SQLite ADO.NET provider.
You can found the System.Data.SQLite provider from SQLite team here:
https://system.data.sqlite.org
Or you can use any libre or commercial provider.
You can also use the free and open-source SQLite ODBC driver that works fine and allow to use VS Visual Designers to create strongly typed ADO.NET DataSets, in addition to the use of OdbcConnection, OdbcCommand and so on:
http://www.ch-werner.de/sqliteodbc
C# Reading data from existing SQLite database

Inner Join two databases to import data - SQL C#

I've created a Winforms app in C#. I do have both my Datasources listed as Datasets.
LOTSDataSet = Source Info
webbitdbdataset = Destination Dataset.
These are connected with LOTSConnectionString and WebbitConnectionString.
Anyway I have the code shown below that I am getting a connection error on, when I try to import data from LOTS to Webbit.
SqlConnection lotscon = new SqlConnection(PackChecker.Properties.Settings.Default["LOTSConnectionString"].ToString());
using (OleDbConnection con = new OleDbConnection(PackChecker.Properties.Settings.Default["WebbitConnectionString"].ToString()))
{
string strgetloc = #"INSERT INTO tblinstitution (
dispenseinstid, institutionname )
SELECT NEWinstitution.institutionid, NEWinstitution.institutionname
FROM NEWinstitution LEFT JOIN tblinstitution ON NEWinstitution.institutionid
= tblinstitution.dispenseinstid
WHERE (((tblinstitution.institutionid) Is Null));";
using (OleDbCommand cmd = new OleDbCommand(strgetloc, con))
{
lotscon.Open();
con.Open();
cmd.ExecuteNonQuery();
con.Close();
lotscon.Close();
}
}
Trying to "OPEN CONNECTION" for both connections was just something I tried.. I guess knowing it was going to fail, but I wanted to try before I asked on here.
The command is attached to the OLEDB connection to Webbit, thus I'm getting an exception based on 'cannot find LOTS server'
Prior to running the query I do run a connection checker, which opens both connections and "tries and catches" both connections to make sure they are valid connections.
Using Access the query does work, so I know the issue 100% is trying to open these connections to two databases!
Any direction would be appreciated.
Gangel

Database failed to open - Login failed for User

I'm currently writing code to save information to a database.
I think I'm at now approaching the last hurdle for getting it to work.
My issue is that when I click save I get a message box saying, Cannot open Database [Database file path] requested by the login. The login failed. Login failed for 'User-PC\User'.
However I didn't create any login details for the database as in the future I want anyone who uses the program to be able to log information into it.
I'm not quite sure where to look to solve the issue, but I am currently downloading SSMS to see if I can fix it there?
Any help would be great, thanks!
My code is,
string constring = "Data Source=(LocalDB)\MSSQLLocalDB;Initial Catalog=c: \users\user\documents\visual studio 2015\Projects\LossApplication\LossApplication\LossDB.mdf;Integrated Security=Yes; Trusted_Connection=True; ";
string query = " insert into LossDB.LossTable (lossid,Equipment, Event, responsinility, start) values(#lossid, #equipment, #Cause, #reason, #start) ;";
SqlConnection conLossDB = new SqlConnection(constring);
SqlCommand cmdLossDB = new SqlCommand(query, conLossDB);
cmdLossDB.Parameters.AddWithValue("#lossid", textBox1.Text);
cmdLossDB.Parameters.AddWithValue("#Equipment", comboBox1.Text);
cmdLossDB.Parameters.AddWithValue("#Cause", comboBox2.Text);
cmdLossDB.Parameters.AddWithValue("#Reason", comboBox3.Text);
cmdLossDB.Parameters.AddWithValue("#start", dateTimePicker1.Text);
//Defines which boxes to read in order to input the text from the defined boxes into the corresponding columns
SqlDataReader myReader;
try
{
conLossDB.Open();
myReader = cmdLossDB.ExecuteReader();
MessageBox.Show("Loss Entry Saved");
//Opens the database and carries out the defined command outlined in the code above
while (myReader.Read())
{
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Using Integrated Security means Windows Authentication mode of the sql server, there must be a valid Windows user that has access to the database. If you want to use this mode and give access to all user on the computer, you can configure Windows Users group (to which all users typically belongs to) to have access to your database (see Security->Logins in your database configuration).
Another approach is to create a SQL user and user SQL Server Authentication mode. Then you use this user login and password to get access to the database regardless of Windows user. In this case your connection string will looks like
(LocalDB)\MSSQLLocalDB;Initial Catalog=<path>\LossDB.mdf;User ID=<UserLogin>;Password=<***>;Trusted_Connection=True;

How to insert data into a Microsoft Access Database?

I'm trying to insert data into a Microsoft Access Database.
I inserted data into the Access database, but the first and second time are the only times that show the data I inserted. When I rebuild my application, the data I inserted is gone. I don't know where they go and not show. I use C# with the .NET framework to develop. Here's the relevant part of the code:
OleDbConnection con = new OleDbConnection(ConfigurationManager.ConnectionStrings["Constr"].ConnectionString);
OleDbCommand com = new OleDbCommand();
com.Connection = con;
com.CommandText = "Insert into Language(English,Type,Thai) values(#eng,#type,#thai)";
com.Parameters.AddWithValue("#eng", english);
com.Parameters.AddWithValue("#type", type);
com.Parameters.AddWithValue("#thai", thai);
con.Open();
com.ExecuteNonQuery();
I wrote that code, but I think it is strange. It doesn't show any errors or exceptions, but my data is not inserted correctly. Is this the correct way to insert data? If so, why it it not getting inserted?
When I rebuild my application, the data I inserted is gone
I suspect your database is being overwritten when the application is rebuilt.
This can happen, for example, if your application contains an MDB file that is copied to the output directory on build, and is used from the output directory.
I think Language should be a reserve word and you should wrap it in [] brackets.
Also consider wrapping the code in using blocks, like
using (OleDbConnection con = new OleDbConnection(...))
{
using (OleDbCommand com = new OleDbCommand(sqlString, con))
{
//code
}
}
Other than this [possible issue with table name and that you are not closing your connection], I don't see anything wrong with the code.
You define parameters for the query, but I don't see anywhere those parameters are bound to actual data...
Try some simple tests that replace the variables you're passing in as parameters with actual values, so you can isolate the problem:
In other words, replace this:
com.Parameters.AddWithValue("#eng", english);
com.Parameters.AddWithValue("#type", type);
com.Parameters.AddWithValue("#thai", thai);
With something like this:
//I don't know the data types of your fields, so I'm guessing
com.Parameters.AddWithValue("#eng", "Test1");
com.Parameters.AddWithValue("#type", myEnum.Latin);
com.Parameters.AddWithValue("#thai", "Test1a");
If that works, then your problem probably lies with the english, type, and thai variables and you'll want to make sure they're getting the data you think they should be getting.
May be ur connection string not correct you can it by using .udl file
just follow the link
http://www.gotknowhow.com/articles/test-a-database-connection-string-using-notepad
You can also check the code shown below
OleDbConnection con = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\Users\\ruby\\Desktop\\screenShots\\ruby.mdb;Persist Security Info=False");
con.Open();
OleDbCommand cmd = new OleDbCommand("insert into raj(Name,Roll) values('XYZ',12);",con);
cmd.ExecuteNonQuery();

Categories