C# Database connection - c#

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();

Related

SqlHelper DataAdapter

I am using a SqlHelper class which has common methods for CRUD operations.
public static void Fill(DataSet dataSet, String procedureName)
{
SqlConnection oConnection = new SqlConnection(DBInterface.ConnectionString);
SqlCommand oCommand = new SqlCommand(procedureName, oConnection);
oCommand.CommandType = CommandType.StoredProcedure;
SqlDataAdapter oAdapter = new SqlDataAdapter();
oAdapter.SelectCommand = oCommand;
oConnection.Open();
using (SqlTransaction oTransaction = oConnection.BeginTransaction())
{
try
{
oAdapter.SelectCommand.Transaction = oTransaction;
oAdapter.Fill(dataSet);
oTransaction.Commit();
}
catch
{
oTransaction.Rollback();
throw;
}
finally
{
if (oConnection.State == ConnectionState.Open)
oConnection.Close();
oConnection.Dispose();
oAdapter.Dispose();
}
}
}
Now in my code, I am calling this method as,
private void BindCustomers()
{
DataSet dsCust = new DataSet();
SqlHelper.Fill(dsCust, "getCustomers");
--then I bind this dataset to datagridview
}
This all works fine. Now I want to update the data in the database. But I am confused how do I call DataAdatpaer.Update(dataset) here to update the changes made in datagridview into database. Is this possible here? Or I need to do it conventionally to find the updated row and call the ExecuteNonQuery function in the SqlHelper? Is there anything which can be done to use dataadapter.update(ds)
Thanks
You don't need to hide data adapter, or if for any reason you did so, you need to expose a method in your class to push updates to server.
Example
Public class SqlHelper
{
string commandText;
string connectionString;
public SqlHelper(string command, string connection)
{
commandText = command;
connectionString = connection;
}
public DataTable Select()
{
var table = new DataTable();
using (var adapter = new SqlDataAdapter(this.commandText, this.connectionString))
adapter.Fill(table)
return table;
}
public void Update(DataTable table)
{
using (var adapter = new SqlDataAdapter(this.commandText, this.connectionString))
{
var builder = new SqlCommandBuilder(adapter);
adapter.Update(table);
}
}
}
By calling this method in your code you can perform all crud operation select, update, delete and insert. you just need to pass connection string, procedure name and parameters list. Using this method you will retrieve data in the DataTable.if anyone want Dataset(Multiple Result) then just need to replace DataSet on the place of DataTable
SqlConnection conn = new SqlConnection("Your ConnectionString");
public DataTable ExecuteDataTable(string ProcedureName, SqlParameter[] _Param)
{
try
{
DataTable dataTable = new DataTable();
SqlCommand cmd = new SqlCommand(ProcedureName, conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Clear();
if (_Param is not null)
{
for (int i = 0; i < _Param.Length; i++)
{
if (_Param[i].ParameterName is not null)
{
if (_Param[i].Value is not null)
{
cmd.Parameters.AddWithValue(_Param[i].ParameterName, _Param[i].Value);
}
else
{
cmd.Parameters.AddWithValue(_Param[i].ParameterName, DBNull.Value);
}
}
}
}
conn.Open();
SqlDataAdapter DA = new SqlDataAdapter(cmd);
DA.Fill(dataTable);
conn.Close();
return dataTable;
}
catch (Exception ex)
{
conn.Close();
throw;
}
}

Not getting any row data from database using c# asp.net.

I can not get any row data from database using c# asp.net.I am trying to fetch one row data from my DB but it is not returning any row.I am using 3-tire architecture for this and i am explaining my code below.
index.aspx.cs:
protected void userLogin_Click(object sender, EventArgs e)
{
if (loginemail.Text.Trim().Length > 0 && loginpass.Text.Trim().Length >= 6)
{
objUserBO.email_id = loginemail.Text.Trim();
objUserBO.password = loginpass.Text.Trim();
DataTable dt= objUserBL.getUserDetails(objUserBO);
Response.Write(dt.Rows.Count);
}
}
userBL.cs:
public DataTable getUserDetails(userBO objUserBO)
{
userDL objUserDL = new userDL();
try
{
DataTable dt = objUserDL.getUserDetails(objUserBO);
return dt;
}
catch (Exception e)
{
throw e;
}
}
userDL.cs:
public DataTable getUserDetails(userBO objUserBO)
{
SqlConnection con = new SqlConnection(CmVar.convar);
try
{
con.Open();
DataTable dt = new DataTable();
string sql = "SELECT * from T_User_Master WHERE User_Email_ID= ' " + objUserBO.email_id + "'";
SqlCommand cmd = new SqlCommand(sql, con);
SqlDataAdapter objadp = new SqlDataAdapter(cmd);
objadp.Fill(dt);
con.Close();
return dt;
}
catch(Exception e)
{
throw e;
}
}
When i am checking the output of Response.Write(dt.Rows.Count);,it is showing 0.So please help me to resolve this issue.
It looks like your your query string has a redundant space between ' and " mark. That might be causing all the trouble as your email gets space in front.
It is by all means better to add parameters to your query with use of SqlConnection.Parameters property.
string sql = "SELECT * from T_User_Master WHERE User_Email_ID=#userID";
SqlCommand cmd = new SqlCommand(sql, con);
cmd.Parameters.Add("#userID", SqlDbType.NVarChar);
cmd.Parameters["#userID"].Value = objUserBO.email_id;

Fill ComboBox with Access DB data

I'm using Visual Studio 2010 and C# to create a windows form with a combobox that should contain employees initials. I have spent the last few days searching through every solution I can find and I still can not get my combobox to populate.
This is what I've got as of now:
public static void FillComboBox(string Query, System.Windows.Forms.ComboBox LoggedByBox)
{
using (var CONN = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\Users\\Documents\\Service Request Application\\bin\\Debug\\servicereq1.mdb"))
{
CONN.Open();
DataTable dt = new DataTable();
try
{
OleDbCommand cmd = new OleDbCommand(Query, CONN);
OleDbDataReader myReader = cmd.ExecuteReader();
dt.Load(myReader);
}
catch (OleDbException e)
{
Console.WriteLine(e.ToString());
Console.ReadLine();
return;
}
LoggedByBox.DataSource = dt;
LoggedByBox.ValueMember = "ID";
LoggedByBox.DisplayMember = "Initials";
}
}
Then I call it when the form loads
private void Form1_Load(object sender, EventArgs e)
{
FillComboBox("select ID, Initials from [Fixers and Testers]", LoggedByBox);
}
When I run the program, the combobox is still blank. I'm positive that my column names and table names are correct. Any suggestions?
I finally got my ComboBox filled and I wanted to share what I changed for anyone else who stumbles across this question in their searches. After spending a bit more time searching through other questions and MSDN, I was able to come up with this.
private void LoadComboLogged()
{
AppDomain.CurrentDomain.SetData("DataDirectory",#"\\prod\ServiceRequests");
string strCon = #"Provider=Microsoft.Jet.OLEDB.4.0;DataSource=|DataDirectory|\servicereq1.mdb";
try
{
using (OleDbConnection conn = new OleDbConnection(strCon))
{
conn.Open();
string strSql = "SELECT Initials FROM [Fixers and Testers] WHERE [Status] ='C'";
OleDbDataAdapter adapter = new OleDbDataAdapter(new OleDbCommand(strSql, conn));
DataSet ds = new DataSet();
adapter.Fill(ds);
loggedByComboBox.DataSource = ds.Tables[0];
loggedByComboBox.DisplayMember = "Initials";
loggedByComboBox.ValueMember = "Initials";
}
}
catch (Exception ex)
{
}
}
I also found that I needed to call
LoadComboLogged();
when I initialized my form. Without that line, the ComboBox would only show a blank dropdown list. Hope this helps someone else who runs into this problem.
Passing control to static method causing this issue. Instead of passing control to the method make that method returns the table and within the load method load the control.
SqlConnection con = new SqlConnection("Data Source=RUSH-PC\\RUSH;Initial Catalog=Att;Integrated Security=True");
con.Open();
SqlDataAdapter da = new SqlDataAdapter("select name from userinfo", con);
DataTable dt = new DataTable();
da.Fill(dt);
DataRow dr;
dr = dt.NewRow();
dt.Rows.InsertAt(dr, 1);
comboBox1.DisplayMember = "name";
comboBox1.ValueMember = "name";
comboBox1.DataSource = dt;
con.Close();
This may help you...
Good luck...:-)
Another possible solution would be to query and return a list of strings. Perhaps it may be less efficient, but it's what I used in a recent project of mine. Here's an example that would reside in a method, possibly called GetInitialsFromDatabase():
using(var conn = new MySqlConnection(connectionString)
{
conn.Open();
using(MySqlCommand cmd = new MySqlCommand())
{
cmd.Connection = conn;
cmd.CommandText = "SELECT Initials FROM [Fixers and Testers] WHERE [Status] ='C'";
MySqlDataReader reader = cmd.ExecuteReader();
while(reader.Read())
{
// initials is a List<String> previously defined (Assuming strings)
initials.Add(String.Format("{0}", reader[0]));
}
}
conn.Close();
}
And then return the initials List, and then in your GUI you could say:
comboBox1.DataSource = returnedList;
comboBox1.DropDownStyle = ComboBoxStyle.DropDownList;

Cannot open Sqlite Database in asp.net

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;
}
}

How to connect C# app with SQLite database

I want to connect to a SQLite database. Please show me example code which WORKS. Also I want to link datagridview with the database.I use this code but it doesn't work:
private DataTable dt;
public Form1()
{
InitializeComponent();
this.dt = new DataTable();
}
private SQLiteConnection SQLiteConnection;
private void DataClass()
{
SQLiteConnection = new SQLiteConnection("Data Source=PasswordManager.s3db;Version=3;");
}
private void GetData()
{
SQLiteDataAdapter DataAdapter;
try
{
SQLiteCommand cmd;
SQLiteConnection.Open(); //Initiate connection to the db
cmd = SQLiteConnection.CreateCommand();
cmd.CommandText = "select*from PasswordManager;"; //set the passed query
DataAdapter = new SQLiteDataAdapter(cmd);
DataAdapter.Fill(dt); //fill the datasource
dataGridView1.DataSource = dt;
}
catch(SQLiteException ex)
{
//Add your exception code here.
}
SQLiteConnection.Close();
You could use the System.Data.SQLite ADO.NET provider. Once you download and reference the assembly, it's pretty straightforward ADO.NET code:
using (var conn = new SQLiteConnection(#"Data Source=test.db3"))
using (var cmd = conn.CreateCommand())
{
conn.Open();
cmd.CommandText = "SELECT id FROM foo";
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
int id = reader.GetInt32(reader.GetOrdinal("id"));
...
}
}
}
In addition to the answer provided by Darin, there is no "create database" command in SQLite (from what I remember). When you initiate a "SQLiteConnection", if the given database (.db3) does not exist, it automatically creates it... from there, you can then create your tables.

Categories