adding and quering the database in visual studio 2012 [closed] - c#

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 9 years ago.
I have added my database as a data source to my C# project in visual studio. Now, I would like to query the database. Do I need to manually set up a connection string with the database?
public void setSQL()
{
string ConnStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Users\\jasper\\Desktop\\AutoReg\\AutoReg.accdb;";
OleDbConnection MyConn = new OleDbConnection(ConnStr);
MyConn.Open();
DataSet ds = new DataSet();
//query to ask
string query = "SELECT * FROM Student";
using (OleDbCommand command = new OleDbCommand(query, MyConn))
{
using (OleDbDataAdapter adapter = new OleDbDataAdapter(command))
{
adapter.Fill(ds);
dataGridView1.DataSource = ds;
MyConn.Close();
}
}
}
Do I need to go through all of this process every time when I need to query a database?

If you're just manually setting up a db connection for literally just one query, there isn't really an easier way to do it. I would suggest that the code be cleaned up a little, though. As it is written in your example, MyConn will remain open if there is an error during your query. That can be fixed by switching it up and putting it in a using:
public void setSQL()
{
string ConnStr = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\jasper\Desktop\AutoReg\AutoReg.accdb;";
DataSet ds = new DataSet();
//query to ask
string query = "SELECT * FROM Student";
using (OleDbConnection MyConn = new OleDbConnection(ConnStr))
{
MyConn.Open();
using (OleDbCommand command = new OleDbCommand(query, MyConn))
{
using (OleDbDataAdapter adapter = new OleDbDataAdapter(command))
{
adapter.Fill(ds);
}
}
}
dataGridView1.DataSource = ds;
}
If you wanted to switch this up and make it easier for you if you need to add more queries in the future, though, then I'd suggest moving to a 3-tier architecture with a Business Logic Layer (BLL) and a Data Access Layer (DAL). In this, you could have a base DAL class that defines some standard methods for things like Fill(), ExecuteScalar(), ExecuteNonQuery(), etc.
You can find countless examples of this kind of set up across the internet, but I've put together a fairly simple example:
Here's a rough sketch of a possible DAL base class. Notice how it manages the actual connections to the database based on a DB command that is passed in:
public abstract class DALBase
{
private const string connStr = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\jasper\Desktop\AutoReg\AutoReg.accdb;";
protected DataSet Fill(OleDbCommand command)
{
DataSet ds = new DataSet();
using (OleDbConnection myConn = new OleDbConnection(connStr))
{
command.Connection = myConn;
myConn.Open();
using (OleDbDataAdapter adapter = new OleDbDataAdapter(command))
{
adapter.Fill(ds);
}
}
return ds;
}
protected void ExecuteNonQuery(OleDbCommand command)
{
using (OleDbConnection myConn = new OleDbConnection(connStr))
{
command.Connection = myConn;
myConn.Open();
command.ExecuteNonQuery();
}
}
// put any other methods you need here
}
And then you can make a table-specific DAL class for your Student table to handle the queries and commands. This keeps your query logic all in one place:
public class StudentDAL : DALBase
{
public DataSet GetAllStudents()
{
DataSet ds = null;
//query to ask
string query = "SELECT * FROM Student";
using (OleDbCommand command = new OleDbCommand(query))
{
ds = Fill(command);
}
return ds;
}
public void UpdateStudentName(int studentID, string name)
{
string query = "UPDATE Student SET Name = #Name WHERE StudentID = #StudentID";
using (OleDbCommand command = new OleDbCommand(query))
{
command.Parameters.AddWithValue("#Name", name);
command.Parameters.AddWithValue("#StudentID", studentID);
ExecuteNonQuery(command);
}
}
}
Then, you would make a table-specific BLL class to handle any intermediary logic that needs to happen between the DAL and the class that needs the information from your database:
public class StudentBLL
{
private _studentDAL = new StudentDAL();
public DataSet GetAllStudents()
{
return _studentDAL.GetAllStudents();
}
public void UpdateStudentName(Student student)
{
_studentDAL.UpdateStudentName(student.StudentID, student.Name);
}
}
In this particular case, the methods pretty much just make calls to the corresponding DAL. If you needed to do any other logic, though (type conversion, some kind of formula, etc.), this is where it would happen. I guess my hypothetical UpdateStudentName method, is a minor example of this. If you look at it, you'll see that it just takes in a Student object and splits it out to send to the DAL. This prevents the UI layer (or other calling class) from needing to worry about this.
Finally, you would make a call to your database through a BLL object from the class that needs the information:
public class SomeOtherClass
{
DataGridView dataGridView1;
public void PopulateDataGridView1()
{
dataGridView1.DataSource = new StudentBLL().GetAllStudents();
}
}
Now, this may not fit exactly into your needs, and I'm sure people could argue about this sort of approach, but this is meant to be more of an example of how you could go about streamlining your data access to make it far more maintainable and scalable down the road.

Related

Database method to work with any type of provider

So far my program only dealt with Sql Server for any type of data work. I would like my program to work with MySql as well. And now that I making this change, I would like to avoid code repetition as much as I can. So I started thinking about having a Factory Pattern with two concrete factories SqlServerFactory and MySqlFactory. This will work! But many of my database methods have pretty much the same structure except that in one, we are using an SqlConnection and SqlCommand and the other we are using a MySqlConnection and the rest of the method code is basically the same. Below is a example of one of my SELECT methods:
public DataTable GetSpyList()
{
DataTable dt = new DataTable();
using (OleDbConnection conn = new OleDbConnection(cs))
{
try
{
string query = "SELECT * FROM SpyList";
OleDbDataAdapter da = new OleDbDataAdapter(query, conn);
conn.Open();
da.Fill(dt);
conn.Close();
return dt;
}
catch (Exception ex)
{
return null;
}
}
}
How can I reduce code repetition by making the above method work for any type of data provider? Is this something that can be achieved by using DbProviderFactories?
Yes, the static DbProviderFactories and the DbProviderFactory class are fit for your purposes.
Of course, every abstraction like this is based on the common functionality of the base classes DbConnection, DbCommand, DbDataReader, DbDataAdapter.
For example. In the MySqlDataReader class you could find an overload of the method GetString that takes as input the name of the column to retrieve. This overload doesn't exists in the SqlDataReader and you need to use the ordinal position of the column to retrieve data. So, in case of DbProviderFactory you could use only the common version of GetString between the MySql provider and the Sql Server provider (IE using the GetString method that takes the ordinal position). Luckily, Intellisense helps a lot to avoid this error.
You could rewrite your code as
public DataTable GetSpyList()
{
DbProviderFactory fac = DbProviderFactories.GetFactory("MySQL.Data.MySqlClient");
DataTable dt = new DataTable();
using(DbConnection conn = fac.CreateConnection())
{
cn.ConnectionString = cs
DbDataAdapter da = fac.CreateDataAdapter();
da.SelectCommand = conn.CreateCommand();
da.SelectCommand.CommandText = "SELECT * FROM SpyList";
try
{
conn.Open();
da.Fill(dt);
return dt;
}
catch (Exception ex)
{
return null;
}
}
}
This example uses a fixed name for the Data Provider, but of course, you could read this name from some kind of configuration file and have your program change its underlying database changing the entry in the configuration file.

How to create database table class

I have a project in c# about a hospital system which contains 30 child forms.
I have created database which contain more than 30 tables.
I created data access like this:
namespace emamTree
{
public class DBAccess
{
public static string connectionString = ConfigurationManager.ConnectionStrings["TreeFinal"].ConnectionString ;
public SqlCommand Intialize(string query, params SqlParameter[] prmArray)
{
SqlConnection cn = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand(query, cn);
if (!query.Contains(" "))
cmd.CommandType = System.Data.CommandType.StoredProcedure;
if (prmArray.Length > 0)
cmd.Parameters.AddRange(prmArray);
cn.Open();
return cmd;
}
public int ExcuteNonQuery(string query, params SqlParameter[] prmArray)
{
try
{
SqlCommand cmd = Intialize(query, prmArray);
int affectedRows = cmd.ExecuteNonQuery();
cmd.Connection.Close();
return affectedRows;
}
catch (SqlException ex)
{
return ex.Number;
}
}
public object ExcuteScalar(string query, params SqlParameter[] prmArray)
{
try
{
SqlCommand cmd = Intialize(query, prmArray);
object value = cmd.ExecuteScalar();
cmd.Connection.Close();
return value;
}
catch (SqlException ex)
{
return ex.Number;
}
}
public SqlDataReader ExcuteReader(string query, params SqlParameter[] prmArray)
{
SqlCommand cmd = Intialize(query, prmArray);
SqlDataReader sqlDataReader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
return sqlDataReader;
}
public DataTable ExcuteDataTable(string query, params SqlParameter[] prmArray)
{
SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(query, connectionString);
if (!query.Contains(" "))
sqlDataAdapter.SelectCommand.CommandType = System.Data.CommandType.StoredProcedure;
if (prmArray.Length > 0)
sqlDataAdapter.SelectCommand.Parameters.AddRange(prmArray);
DataTable dt = new DataTable();
sqlDataAdapter.Fill(dt);
return dt;
}
public DataSet ExcuteDataSet(string query, params SqlParameter[] prmArray)
{
SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(query, connectionString);
if (!query.Contains(" "))
sqlDataAdapter.SelectCommand.CommandType = System.Data.CommandType.StoredProcedure;
if (prmArray.Length > 0)
sqlDataAdapter.SelectCommand.Parameters.AddRange(prmArray);
DataSet ds = new DataSet();
sqlDataAdapter.Fill(ds);
return ds;
}
}
}
In form patient(Table Patient) I create save method and works fine:
public void Save()
{
DBAccess db = new DBAccess();
db.ExcuteNonQuery("insert into Patients (FileNum,PatientTypeID,EngName,NationalityID,RelegionID) values (#FileNum,#PatientTypeID,#EngName,#NationalityID,#RelegionID)",
new SqlParameter("#FileNum", txtFileNum.Text),
new SqlParameter("#PatientTypeID", txtPatientTypeID.Text),
new SqlParameter("#EngName", txtEngName.Text),
new SqlParameter("#NationalityID", txtNationalityID.Text),
new SqlParameter("#RelegionID", txtRelegionID.Text)
);
}
My question is how to make classes for each table in the database?
Use existing solutions like EntityFramework. It provided all the functionality you need and it will make your life much easier than writing it all yourself (and I know, I have done it).
Creating a data access layer is a very critical part of any application. It has to be a separate library so that you can use it in any project today and in the future. Say, tomorrow you want your windows app to be converted to a web application! You can add the DAL libray and start using it.
Having said that, building your own DAL is time cosuming and its like reinventing the wheel. So you need to explore available options which might suite your requirements. Out of the box you have an ORM called EntityFramework. Its pretty straight forward to use but performace wise, its slow compared to handwritten sql. There is also another popular ORM called NHibernate. Its original counterpart Hibernate is huge in java community but it has a very steep learning curve.
But i like to use PetaPoco. It gives best of both worlds. ORM + sql. There are also other such micro ORMs like Dapper, Massive, etc. You need try each one of them and pick the one that suits your application at hand.
Even after choosing a framework that fits your bill, you need to create abstractions to make sure you can change frameworks later if required. Creating a proper DAL is a huge undertaking and has taken big chunk of my time as a developer to get things right. You can explore and find it out by your self. Good luck.

How to display data in gridview from MS Access?

I want to display information of user stored in a MS Access database. The user enters his userid and on clicking a button following function is called. But no data is being displayed. What am I doing wrong ?
System.Data.OleDb.OleDbConnection con;
System.Data.OleDb.OleDbDataAdapter da;
protected void Button1_Click(object sender, EventArgs e)
{
con = new System.Data.OleDb.OleDbConnection();
con.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;"
+ "Data Source=C:\\Users\\sam\\Desktop\\mydb.mdb";
con.Open();
string sql = "SELECT * From Leave where userid="+Textbox1.Text;
da = new System.Data.OleDb.OleDbDataAdapter(sql, con);
DataTable t = new DataTable();
da.Fill(t);
GridView1.DataSource = t;
con.Close();
}
You need to call GridView1.DataBind()
GridView1.DataSource = t;
GridView1.DataBind();
Just a side-note, it is good practice to wrap your connection with using
using(con = new System.Data.OleDb.OleDbConnection())
{
con = new System.Data.OleDb.OleDbConnection();
con.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;"
+ "Data Source=C:\\Users\\sam\\Desktop\\mydb.mdb";
con.Open();
...
...
}
This ensures your connection is properly disposed after use
You should use bind function:
protected void Button1_Click(object sender, EventArgs e)
{
con = new System.Data.OleDb.OleDbConnection();
con.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;"
+ "Data Source=C:\\Users\\sam\\Desktop\\mydb.mdb";
con.Open();
string sql = "SELECT * From Leave where userid="+Textbox1.Text;
da = new System.Data.OleDb.OleDbDataAdapter(sql, con);
DataTable t = new DataTable();
da.Fill(t);
GridView1.DataSource = t;
GridView1.DataBind();
con.Close();
}
First off, please, please please don't concatenate your WHERE parameters in your SQL. Use Parameters. Second, Add a "using System.Data.OleDb" statement at the top of your module, so that you are not having to type things like:
System.Data.OleDb.OleDbDataAdapter
Over and over again.
Try the following code. Personally, when I have to work with data tables and such, I prefer to avoid all the DataAdapter nonsense, and keep it as simple as possible.
Note in the code below:
the "using" blocks. These place the variables created within them inside their own scope, and take care of disposal and such for you.
I used an OleDb Parameter instead of concatenating criteria. This is a much safer way to do things, and creates much cleaner and more readable code as well, especially in cases where you have several criteria in your WHERE clause.
I assume your UserID input is a string, since you are grabbing the value from a Textbox. If it is in fact an int value (such as an auto-incrementing id in MS Access) you will need to use an int data type instead. You may have to mess with it a little. When you are still figuring this stuff out, it can be a bit painful. However, using parameters increases security and maintainability.
Once you have obtained a data table as the return from the MyUsers method, you should be able to simply set the data source of your Gridview. If you have difficulties still, do as Steve suggests and check the Autogenerate columns property in the designer, or set it in code.
Not that I have moved the connection string to the project Properties/Settings. You should find this in the solution designer. Place your connection string there, in one spot, and you can obtain it from anywhere in your code. If you later change the connection string (such as moving your Db to another computer, server share, etc) you need only change it in one place.
SAMPLE CODE:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.OleDb; // put this here, and stop writing long namespaces inline
namespace WindowsFormsApplication3
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
// Where possible, move code out of specific event handlers
// into methods which can be re-used from other client code.
// Here, I pulled the actual data access out into separate methods,
// and simply call it from the event handler:
this.LoadGridView(textBox1.Text);
}
private void LoadGridView(string UserID)
{
// Now we can load the gridview from other places in our
// code if needed:
this.dataGridView1.DataSource = this.MyUsers(UserID);
}
private DataTable MyUsers(string UserID)
{
var dt = new DataTable();
// Use a SQL Paramenter instead of concatenating criteria:
string SQL = "SELECT * FROM Leave WHERE userid = #UserID";
// The "using" statement limits the scope of the connection and command variables, and handles disposal
// of resources. Also note, the connection string is obtained from the project properties file:
using(OleDbConnection cn = new OleDbConnection(Properties.Settings.Default.MyConnectionString))
{
using (var cmd = new OleDbCommand(SQL, cn))
{
// For simpler things, you can use the "AddWithValue" method to initialize a new parameter,
// add it to the Parameters collection of the OleDBCommand object, and set the value:
cmd.Parameters.AddWithValue("#UserID", UserID);
// Get in, get out, get done:
cn.Open();
dt.Load(cmd.ExecuteReader());
cn.Close();
}
}
return dt;
}
}
}
Hope that helps. It's not how everyone might do it, but I have found it provides maximum flexibility, when you must work with MS Access.

It don't get any data from DataReader

i work with N tiers tec in C# for ado, trying to make it easy to use and capable to change any database kind with out write all the cod all over again ,
my code here doesn't get any error but it doesn't get any values to my textbox
(i am trying to get data from table to many textboxs to update it later)
and here how code works:{
at first i make some functions to take any set any kind of parameters or set any command and then i make other function to to execute what ever i set or get from database all that Function i build it in folder name (Data Access Layer)
then i made other folder (Data Build layer)to take use all those function for what ever i want to do in any page (insert , update , delete , Select),
the last think i do it to call the function i made at at (Data Build layer) to my page or control ,
i do all that because if i Change the database Type ,i change only one class and other classes still the same
i hope i explain enough (sorry for my English not good enough)}
Code :
Class DataAccessLayer
public static void Setcommand (SqlCommand cmd,CommandType type,string commandtext)
{
cmd.CommandType=type;
cmd.CommandText=commandtext;
}
public static void AddSQLparameter(SqlCommand cmd, int size,SqlDbType type,object value,string paramName,ParameterDirection direction)
{
if (cmd == null)
{
throw (new ArgumentException("cmd"));
}
if (paramName == null)
{
throw (new ArgumentException("paramName"));
}
SqlParameter param=new SqlParameter();
param.ParameterName= paramName;
param.SqlDbType=type;
param.Size=size;
param.Value=value;
param.Direction=direction;
cmd.Parameters.Add(param);
}
public static SqlDataReader ExecuteSelectCommand(SqlCommand cmd)
{
if (cmd == null)
{
throw (new ArgumentNullException("cmd"));
}
SqlConnection con = new SqlConnection();
cmd.Connection = con;
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
con.Close();
return dr ;
}
Class DatabuildLayer
SqlCommand com;
public DatabuildLayer()
{
com = new SqlCommand();
//
// TODO: Add constructor logic here
//
}
public SqlDataReader SelectCatalog(int catid)
{
DataAccessLayer.Setcommand(com, CommandType.Text, "select catname,catdescription,photo from category where catid=#catid" );
DataAccessLayer.addSQLparameter(com,16,SqlDbType.Int,catid,"#catid",ParameterDirection.Input);
return DataAccessLayer.ExecuteSelectCommand(com);;
}
and here my last code that retrieve my data to some textbox
in my Pageload :
protected void Page_Load(object sender, EventArgs e)
{
DatabuildLayer= new DatabuildLayer();
SqlDataReader dr ;
dr = obj.SelectCatalog(catselectddl.SelectedIndex);
if (dr.Read())
{
catnametxt.Text = dr["catname"].ToString();
catdestxt.Text = dr["catdescription"].ToString();
}
}
Is it possible that the query is returning nothing, and dr.Read() is returning false? Assuming the code actually executes (it is hard to tell from here) that is probably the only thing that would stop it working - either that or empty columns.
For what it is worth I think that your code needs to be tidied up a bit from a structural and conventions point of view. You should probably look through your code and consider the naming guidelines for the .NET framework. When others read your code they will want it formatted and consistent with this documentation. http://msdn.microsoft.com/en-us/library/xzf533w0(v=vs.71).aspx
Further, most people doing ASP.NET these days try to look for some way to inject external dependencies (such as databases) into their code using a framework like WebFormsMVP available at
http://webformsmvp.com/ in conjunction with an IoC container like autofac available at http://code.google.com/p/autofac/.
Using this approach you can push all external dependencies out of your application behind interfaces which would make it fairly trivial to plug in a different database engine.
Your current wrapper code is not doing anything particularly useful (just subsituting the existing methods or your own tht do the same thing), and it is not closing the connections correctly. It is... a bit of a mess.
If you aren't already massively familiar with the raw ADO.NET interfaces, then maybe consider something like "dapper" which will do all this for you, with a sane API:
short catid = 16;
using(var conn = GetOpenConnection()) {
var row = conn.Query(
"select catname,catdescription,photo from category where catid=#catid",
new { catid }).FirstOrDefault();
if(row != null) {
string name = row.catname, desc = row.catdescription;
// ...
}
}
Or if you have a class with CatName / CatDescription properties:
var obj = conn.Query<Catalogue>(
"select catname,catdescription,photo from category where catid=#catid",
new { catid }).FirstOrDefault();
from my experience, when you close a connection associated with a DataReader, nothing can be retrieved from the reader anymore.
//You closed the connection before returning the dr in the your method below:
public static SqlDataReader ExecuteSelectCommand(SqlCommand cmd)
{
if (cmd == null)
{
throw (new ArgumentNullException("cmd"));
}
SqlConnection con = new SqlConnection();
cmd.Connection = con;
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
con.Close(); //here your connection was already closed
return dr ; //this dr is disconnected
}

Issues querying Access '07 database in C#

I'm doing a .NET unit as part of my studies. I've only just started, with a lecturer that as kinda failed to give me the most solid foundation with .NET, so excuse the noobishness.
I'm making a pretty simple and generic database-driven application. I'm using C# and I'm accessing a Microsoft Access 2007 database.
I've put the database-ish stuff in its own class with the methods just spitting out OleDbDataAdapters that I use for committing. I feed any methods which preform a query a DataSet object from the main program, which is where I'm keeping the data (multiple tables in the db).
I've made a very generic private method that I use to perform SQL SELECT queries and have some public methods wrapping that method to get products, orders.etc (it's a generic retail database).
The generic method uses a separate Connect method to actually make the connection, and it is as follows:
private static OleDbConnection Connect()
{
OleDbConnection conn = new OleDbConnection(
#"Provider=Microsoft.ACE.OLEDB.12.0; Data Source=C:\Temp\db.accdb");
return conn;
}
The generic method is as follows:
private static OleDbDataAdapter GenericSelectQuery(
DataSet ds, string namedTable, String selectString)
{
OleDbCommand oleCommand = new OleDbCommand();
OleDbConnection conn = Connect();
oleCommand.CommandText = selectString;
oleCommand.Connection = conn;
oleCommand.CommandType = CommandType.Text;
OleDbDataAdapter adapter = new OleDbDataAdapter();
adapter.SelectCommand = oleCommand;
adapter.MissingSchemaAction = MissingSchemaAction.AddWithKey;
adapter.Fill(ds, namedTable);
return adapter;
}
The wrapper methods just pass along the DataSet that they received from the main program, the namedtable string is the name of the table in the dataset, and you pass in the query you wish to make.
It doesn't matter which query I give it (even something simple like SELECT * FROM TableName) I still get thrown an OleDbException, stating that there was en error with the FROM clause of the query. I've just resorted to building the queries with Access, but there's still no use. Obviously there's something wrong with my code, which wouldn't actually surprise me.
Here are some wrapper methods I'm using.
public static OleDbDataAdapter GetOrderLines(DataSet ds)
{
OleDbDataAdapter adapter = GenericSelectQuery(
ds, "orderlines", "SELECT OrderLine.* FROM OrderLine;");
return adapter;
}
They all look the same, it's just the SQL that changes.
Have you tried something more simple to see if you have connectivity to the table you are looking for. Something like
DataSet ds = new DataSet();
using (OleDbConnection myConnection = new OleDbConnection
(#"Provider=Microsoft.ACE.OLEDB.12.0; Data Source=C:\Temp\db.accdb"))
{
myConnection.Open();
OleDbDataAdapter myAdapter = new OleDbDataAdapter("SELECT OrderLine.* FROM OrderLine;, myConnection);
myAdapter.TableMappings.Add("Table", "TestTable");
myAdapter.Fill(ds);
}
Then from there check to see if stuff is in ds with
ds.Tables[0].Rows.Count()
This will actually show you if you are hitting the DB and getting results. From there you can make it more elegant
Square brackets seem to have fixed the problem. Turns out I was using a keyword. Hmph.

Categories