My project should display data from an sqlite3 database. The database name is db.sqlite3.
The error is: Unable to open the database file
here is my code:
public partial class OverviewAdmin : System.Web.UI.Page
{
private SQLiteConnection sql_con;
private SQLiteCommand sql_cmd;
private SQLiteDataAdapter DB;
private DataSet DS = new DataSet();
private DataTable DT = new DataTable();
protected void Page_Load(object sender, EventArgs e)
{
LoadData();
}
private void SetConnection()
{
sql_con = new SQLiteConnection
("Data Source=db.sqlite3;");
}
private void LoadData()
{
SetConnection();
sql_con.Open();
sql_cmd = sql_con.CreateCommand();
string CommandText = "select * from scotty_fahrt";
DB = new SQLiteDataAdapter(CommandText, sql_con);
DS.Reset();
DB.Fill(DS);
DT = DS.Tables[0];
GVOutput.DataSource = DT;
sql_con.Close();
}
Maybe its because of the database file name.
Put your database file in the APP_DATA subfolder of your site and change the method that sets the connection to
private void SetConnection()
{
sql_con = new SQLiteConnection
("Data Source=|DataDirectory|\\db.sqlite3;");
}
By the way, I would remove the global variable for the connection and change your SetConnection to return the SQLiteConnection. This will allow to apply the using statement to correctly handle disposable like a connection also in case of exceptions
private SQLite GetConnection()
{
return new SQLiteConnection("Data Source=|DataDirectory|\\db.sqlite3;");
}
private void LoadData()
{
using(SQLiteConnection cn = GetConnection())
{
cn.Open();
string CommandText = "select * from scotty_fahrt";
DB = new SQLiteDataAdapter(CommandText, sql_con);
DS.Reset();
DB.Fill(DS);
DT = DS.Tables[0];
GVOutput.DataSource = DT;
}
}
Related
this is my code
i have tried every step i can find
i have moved con.close(); before and after it is still not working
please guide me to what to do
thank you
I am following this youtube video to make the crud operation https://www.youtube.com/watch?v=C7ukAjQtsxE
using System.Data;
using System.Data.SqlClient;
namespace crudingtime
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
SqlConnection con = new SqlConnection("Data Source=DESKTOP-6381H14\\SQLEXPRESS;Initial Catalog=yarabthis;Integrated Security=True");
private void Form1_Load(object sender, EventArgs e)
{
GetEmpList();
}
private void imtired_Click(object sender, EventArgs e)
{
con.Open();
int id = int.Parse(idbox.Text);
string fname=fnametxt.Text, lname=lnametxt.Text;
SqlCommand c = new SqlCommand("exec ughh'"+id+"','"+fname+"','"+lname+"','",con);
con.Close();
MessageBox.Show("Successfully inserted");
}
void GetEmpList()
{
SqlCommand c = new SqlCommand("exec Listughh", con);
SqlDataAdapter sd=new SqlDataAdapter(c);
DataTable dt = new DataTable();
sd.Fill(dt);
dataGridView1.DataSource = dt;
}
}
}```
don't try and persist the connection at the form class level - since then you can't control when you dispose of it.
So, try say like this, and always have a using code block (which will clean up all your connections for you).
And it not clear why you have a public form method here, so let's just leave that issue out of the picture for the time being.
and I assume that a hard coded connection string was JUST for this post, not that you are using hard coded connection strings all over the place - (don't do that!!!).
And you tagged this as asp.net so we assuem this is a web page, right?
Thus, this "air code" should suffice:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
GetEmpList();
}
private void imtired_Click(object sender, EventArgs e)
{
int id = int.Parse(idbox.Text);
SqlCommand c = new SqlCommand("ughh");
c.Parameters.Add("#ID", SqlDbType.Int).Value = id;
c.Parameters.Add("#fname", SqlDbType.NVarChar).Value = fnametxt.Text;
c.Parameters.Add("#lname", SqlDbType.NVarChar).Value = lnametxt.Text;
MyRstP(c, false);
MessageBox.Show("Successfully inserted");
}
void GetEmpList()
{
SqlCommand c = new SqlCommand("Listughh");
DataTable dt = new DataTable();
DataGridView1.DataSource = MyRstP(c);
DataGridView1.DataBind();
}
public DataTable MyRstP(SqlCommand cmdSQL, bool returnData = true)
{
DataTable rstData = new DataTable();
using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.TEST4))
{
using (cmdSQL)
{
cmdSQL.Connection = conn;
conn.Open();
cmdSQL.CommandType = CommandType.StoredProcedure;
if (returnData)
{
rstData.Load(cmdSQL.ExecuteReader());
}
else
{
cmdSQL.ExecuteNonQuery();
}
}
}
return rstData;
}
And as for that file in use.
Reboot your computer.
So, "isolate" your connection routine(s). Don't attempt to persist the connection at the form/class level, move your connection string to config or settings. (and bonus points is you can use the connection builder).
I am trying to make it so that when changing the value in the comboBox, the database is displayed in the dataGridview. Everything seems to work, but when you close the form it gives an error:
enter image:
Code:
namespace Cursach
{
public partial class VoucherForm : Form
{
public VoucherForm()
{
InitializeComponent();
}
public void VoucherCountry()
{
dataGridView1.AllowUserToAddRows = false;
dataGridView1.AllowUserToDeleteRows = false;
dataGridView1.AllowUserToOrderColumns = false;
dataGridView1.AllowUserToResizeRows = false;
dataGridView1.AllowDrop = false;
dataGridView1.ReadOnly = true;
DB dB = new DB();
SqlCommand command = new SqlCommand("SELECT * FROM Voucher WHERE Name_Country= #nC", dB.ConnectionSQL());
command.Parameters.Add("#nC", SqlDbType.VarChar).Value = comboBox1.SelectedValue;
DataTable table = new DataTable();
SqlDataAdapter adapter = new SqlDataAdapter();
dB.OpenSQL();
adapter.SelectCommand = command;
adapter.Fill(table);
dataGridView1.DataSource = table;
dB.ClodeSQL();
}
private void VoucherForm_Load(object sender, EventArgs e)
{
this.countryTableAdapter.Fill(this.cursacDat.Country);
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
VoucherCountry();
}
}
You have a DB class which is good to separate you database code from your user interface code. I moved the database code to retrieve the Country data to the DB class. Notice how the DB class knows nothing about the user interface and the user interface knows nothing about the database.
Database objects need to be closed and disposed. using blocks take care of this for you even if there is an error.
public class DB
{
private string ConStr = "Your connection string";
public DataTable GetCountryData(string nC)
{
DataTable dt = new DataTable();
using (SqlConnection cn = new SqlConnection(ConStr))
using (SqlCommand cmd = new SqlCommand("SELECT * FROM Voucher WHERE Name_Country= #nC", cn))
{
cmd.Parameters.Add("#nC", SqlDbType.VarChar, 100).Value = nC;
cn.Open();
dt.Load(cmd.ExecuteReader());
}
return dt;
}
}
Then in the form.
private void OpCode()
{
if (comboBox1.SelectedIndex < 0)
{
MessageBox.Show("Please select a value in the drop down.");
return;
}
DB DataClass = new DB();
dataGridView1.DataSource = DataClass.GetCountryData(comboBox1.SelectedValue.ToString());
}
I try to make connection with MySQL db using this class.
public class DataManager
{
// Connection String
public static string constr = ConfigurationManager.ConnectionStrings["cnn1"].ConnectionString;
public static DataSet GetDataSet(string stored_name, string table_name, params MySqlParameter[] prmarr)
{
MySqlConnection con = new MySqlConnection(constr);
MySqlCommand cmd = new MySqlCommand(stored_name,con);
cmd.CommandType = CommandType.StoredProcedure;
foreach (MySqlParameter prm in prmarr)
{
cmd.Parameters.Add(prm);
}
DataSet ds = new DataSet();
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
da.Fill(ds,table_name);
return ds;
}
then I called it in load event of page that is inhered from master page
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
// product_select is stored procedure/ routine that I made it in db
using (DataSet ds = DataManager.GetDataSet("product_select","x")) // error is here
{
DataList1.DataSource = ds.Tables["x"];
DataList1.DataBind();
}
}
}
when I run,I get this error.
An exception of type 'System.Collections.Generic.KeyNotFoundException' occurred in mscorlib.dll
{"The given key was not present in the dictionary."}
my stored procedure in xampp db
DELIMITER $$
CREATE DEFINER=`root`#`localhost` PROCEDURE `product_select`()
NO SQL
SELECT 'P_id','name','unit_price','image_product' FROM product$$
DELIMITER ;
I have a homework about database connection via ms access.
I prepared my database and saved it as dbMert and put it to debug / bin
This is my CustomerDatabase class for connecting to database:
static class CustomerDatabase
{
static string connectionstring = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=dbMert.mdb";
static OleDbConnection connection = null;
static OleDbCommand command = null;
public static void ConnectToDatabase()
{
if (connection == null)
{
connection = new OleDbConnection(connectionstring);
command = new OleDbCommand();
command.Connection = connection;
command.CommandText = "select * from Customer";
}
}
public static DataTable executeSelect(string sql)
{
ConnectToDatabase();
DataTable dt = null;
dt = new DataTable();
command.CommandText = sql;
OpenConnection();
OleDbDataReader datareader = command.ExecuteReader();
dt.Load(datareader);
datareader.Close();
CloseConnection();
return dt;
}
public static void OpenConnection()
{
try
{
if (connection != null)
{
connection.Open();
}
}
catch (Exception ex)
{
}
}
public static void CloseConnection()
{
if (connection != null)
{
connection.Close();
}
}
}
}
Form: In constructor i try to connect to database
public Form1()
{
InitializeComponent();
CustomerDatabase.ConnectToDatabase();
}
and in form's load i try to take tuples to datagridview but nothing happens :S
private void Form1_Load(object sender, EventArgs e)
{
string sql1 = "select * from Customer";
DataTable dt = CustomerDatabase.executeSelect(sql1);
}
Regardless of other things (such as not keeping a single connection open, using using statements etc) you're not connecting your newly-loaded DataTable to your DataGridView at all. Your Form1_Load method just loads the data into a DataTable, then effectively throws it away.
I suspect you want something like:
dataGridView.DataSource = dt;
at the end of the method.
EDIT: Note that this is also a really bad idea in your OpenConnection code:
catch (Exception ex)
{
}
That basically says, "If something goes wrong, don't bother recording that fact or changing how the rest of the code works - just keep going as if nothing had happened."
Why are you catching the exception at all?
Try to write simple code. I suggest you to use OleDbDataAdaper, its Fill() method populate the DataTable easily.
You may use |DataDirectory| if you are using database (.mdb) located under Bin\Debug folder.
static string connectionstring = #"Provider=Microsoft.ACE.OLEDB.12.0;
Data Source=|DataDirectory|\dbMert.mdb";
Or
static string connectionstring = #"Provider=Microsoft.ACE.OLEDB.12.0;
Data Source=x:\full_path\dbMert.mdb";
Or
static string connectionstring = #"Provider=Microsoft.Jet.OLEDB.4.0;
Data Source=x:\full_path\dbMert.mdb";
static class Test
{
static string connectionstring = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=dbMert.mdb";
public static DataTable executeSelect(string sql)
{
DataTable dt = new DataTable();
OleDbDataAdapter adapter = new OleDbDataAdapter(sql,connectionString);
adapter.Fill(dt);
return dt;
}
}
Add following code in form_load handler,
string sql1 = "select * from Customer";
DataTable dt = Test.executeSelect(sql1);
DataGridView1.DataSource=dt;
When I move the DB-file to bin/debug, an error message states "4.0 is not installed".
However, when I move it to bin, the problem is solved.
My code:
con.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source= ..\\dbMert.mdb";
con.Open();
recordları
DataSet ds = new DataSet();
DataTable dt = new DataTable();
ds.Tables.Add(dt);
OleDbDataAdapter da = new OleDbDataAdapter();
da = new OleDbDataAdapter("Select * from Customer", con);
da.Fill(dt);
dataGridView1.DataSource = dt;
foreach (DataRow row in dt.Rows)
{
foreach (DataColumn col in dt.Columns)
if(col.ToString() == "emailAdress")
comboBox1.Items.Add(row[col]);
}
con.Close();
I took an video from you tube to Retrieving Data from SQL Server using C# and ADO.Net
http://www.youtube.com/watch?v=4kBXLv4h2ig&feature=related
I Do the same as him in the video...
I want to show data from an sql database in a DataGridView.
I get an error whit
da.Fill(dg);
dg.DataSource = dg.Tables[0];
I name my DataGridView dg...
Complete code
using System.Data.SqlClient;
namespace SQLconnection
{
public partial class Form1 : Form
{
SqlConnection cs = new SqlConnection("Data Source=FRANK-PC\\SQLEXPRESS; Initial Catalog=Forc#; Integrated Security=TRUE");
SqlDataAdapter da = new SqlDataAdapter();
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
da.InsertCommand= new SqlCommand ("INSERT INTO tblContacts VALUES (#FirstName,#LastName)", cs );
da.InsertCommand.Parameters.Add("#FirstName", SqlDbType.VarChar).Value = txtFirstName.Text;
da.InsertCommand.Parameters.Add("#LastName", SqlDbType.VarChar).Value = txtLastname.Text;
cs.Open();
da.InsertCommand.ExecuteNonQuery();
cs.Close();
}
// Display data in dg
private void button2_Click(object sender, EventArgs e)
{
da.SelectCommand = new SqlCommand("SELECT * FROM tblContacts", cs);
da.Fill(dg);
dg.DataSource = dg.Tables[0];
}
}
}
you should open the connection before filling the table with the data adapter, add this:
cs.Open();
DataSet ds = new DataSet();
da.Fill(ds);
cs.Close();
dg.DataSource = ds.Tables[0];
note that this is anyway a bad practice, there are trillions of examples here in SO on how to handle the SQLConnections, you should use a using block so that it gets closed and disposed immediately after usage and do not have connections or adapters or data tables or sqlcommand global to all form but create them only when/where needed.
You should actually move out all data access logic from the UI to a separated class, Business Logic or Data layer.
Edit:
you should do something like this:
using(SQLConnection conn = 'connection string here')
{
using(SQLCommand cmd = new ('sql query', conn))
{
//execute it blah blah
}
}
check out this question: Closing SqlConnection and SqlCommand c#
The Fill method open/close connection implicitly but the problem is in name of dataGrdiView and DataTable/DataSet reference variable - dg
private void button2_Click(object sender, EventArgs e)
{
da.SelectCommand = new SqlCommand("SELECT * FROM tblContacts", cs);
DataTable dt=new DataTable();
da.Fill(dt);
dg.DataSource = dt;
}
I'm guessing since you didn't include the exception you are receiving, but you need to open your SqlConnection prior to using it:
private void button2_Click(object sender, EventArgs e)
{
da.SelectCommand = new SqlCommand("SELECT * FROM tblContacts", cs);
cs.Open();
da.Fill(dg);
cs.Close();
dg.DataSource = dg.Tables[0];
}
Try it this, but is important know what kind of exception throws.
private void button2_Click(object sender, EventArgs e)
{
cs.Open();
using (SqlDataAdapter a = new SqlDataAdapter("SELECT * FROM tblContacts", cs))
{
DataTable t = new DataTable();
a.Fill(t);
dg.DataSource = t;
}
}