Working with database confusion in C# - c#

I am trying to learn about how to work with databases in C# and I have gotten to a part in a tutorial when I have to work with DataSet , SqlDataAdapter and SqlCommandBuilder.This is the code I wrote in the example in the tutorial:
public void InitData() {
//instantiate the connection
conn = new SqlConnection("Data Source=.\\SQLEXPRESS;AttachDbFilename=\"D:\\Projects IDE\\Visual Studio\\Exercitii\\Console.app\\WindowsFormsApplication1\\WindowsFormsApplication1\\PlanetWrox.mdf\";Integrated Security=True;User Instance=True");
//1.instantiate a new DataSet
dsCustomers = new DataSet();
//2.init SqlDataAdapter with select command and connection
daCustomers = new SqlDataAdapter("SELECT Id ,Name, SortOrder FROM Genre", conn);
// 3. fill in insert, update, and delete commands
SqlCommandBuilder cmdBldr = new SqlCommandBuilder(daCustomers);
// 4. fill the dataset
daCustomers.Fill(dsCustomers, tableName);
}
public void btnUpdateClicked(object sender, EventArgs e) {
// write changes back to DataBase
daCustomers.Update(dsCustomers, tableName);
}
There are a couple of things I do not understand here:
The first thing I noticed is that I do not have to open and close the database.From what limited knoledge I have about databases I know that in order to acces the data you have to open a connection to it and after you are done you have to close it.This must happen somewhere behind the scene.Is that righT? If that is so witch method does that?
The second question is regarding the SqlDataAdapter and SqlCommandBuilder.I do not understand what does SqlCommandBuilder does here.Isen't the SqlDataAdapter the one that is executing the sql query?

The first thing I noticed is that I do not have to open and close the
database.
SqldataAdapter.Fill will open/close the connection for you.
If the IDbConnection is closed before Fill is called, it is opened to
retrieve data and then closed. If the connection is open before Fill
is called, it remains open.
The SqlCommandBuilder generates INSERT, UPDATE, or DELETE statements from the metadata of your provided select-statement. On this way you can call daCustomers.Update and all changes made to the DataSet will automatically be updated in the database.

dsCustomers.Fill opens and closes connection for you.
SqlCommandBuilder creates insert, update, and delete based on your select statement.

ADO.NET handles that task for you, when you Fill your table with data

//instantiate the connection
using (SqlConnection conn = new SqlConnection("Data Source=.\\SQLEXPRESS;AttachDbFilename=\"D:\\Projects IDE\\Visual Studio\\Exercitii\\Console.app\\WindowsFormsApplication1\\WindowsFormsApplication1\\PlanetWrox.mdf\";Integrated Security=True;User Instance=True"))
{
//1.instantiate a new DataSet
dsCustomers = new DataSet();
//2.init SqlDataAdapter with select command and connection
daCustomers = new SqlDataAdapter("SELECT Id ,Name, SortOrder FROM Genre", conn);
// 3. fill in insert, update, and delete commands
SqlCommandBuilder cmdBldr = new SqlCommandBuilder(daCustomers);
// 4. fill the dataset
daCustomers.Fill(dsCustomers, tableName);
}
This would automatically close the connection and Dispose, without you having to bother about it.

Fill will make the all the resources locked that are involved in the process.
Also as per the sql settings it may block other resources too.
If you are using this code for some real time work..Please choose it only if you need this.

For your first thing:
We use conn.open(); to open the connection and conn.close(); to close the connection.
Here in your program you are not connecting to database like to sqlserver. You have provided shown physical path to the file.
See the below for second thing:
SqlCommandBuilder Class

Related

Using MySql.Data with C# while not making a MySqlConnection

The reccomended way to use MySql.Data is to NOT use a MySqlConnection object; as explained in the documentation. This allows for the MySQl.Data API code to handle connection pooling correctly.
See: mySQL documentation
So, for example, this code Selects data with the connection string passed in as a parameter.
The MySqlConnection object is created in the background:
DataSet dataset = new DataSet();
MySqlDataAdapter adapter = new MySqlDataAdapter("select * from cfx_jobs", _mySqlConnectionString);
adapter.Fill(dataset);
return dataset;
I have looked around and I cannot find an example of how to Insert into the database without explicitly creating a MySqlConnection object.
Which method should I use?
This is how to do it.
MySqlHelper.ExecuteNonQuery(_mySqlConnectionString, sqlStatement);

How to close a table with the VFP OLE DB Provider

I'm writing some software in C# that will perform queries on Visual FoxPro datafiles over time. I need to be able to close tables, especially those that are opened exclusively ("Mode=Share Exclusive" in the Connection String), but the only way I can seem to do that is by closing the entire OleDbConnection.
The VFP OLE DB Provider supports some syntax from VFP itself, but commands that would close a table in standard VFP, such as USE, either do not work, or throw an exception (I can't recall which command threw an exception at the moment).
Currently, each instance of a class has its own OleDbConnection property, so that if I need to, I'm able to close it and release the table it works on. While this works, it's not optimal, and I'd prefer to have 1 connection instance.
// Elsewhere, ideally one connection for the entire process,
// if I'm able to release locks
public OleDbConnection Connection { get; } = new OleDbConnect();
// ...
if(Connection.State == ConnectionState.Closed) {
Connection.ConnectionString = "Provider=vfpoledb.dll;Data Source=J:\\epdata\\;Mode=Share Exclusive"
Connection.Open();
}
OleDbCommand cmd = new OleDbCommand("SET DELETED OFF", Connection);
cmd.ExecuteNonQuery();
cmd.CommandText = "SELECT * FROM tran";
OleDbDataAdapter adap = new OleDbDataAdapter(cmd);
DataTable table = new DataTable();
adap.Fill(table);
// Something here to release the lock on the tran table
This works to the point where it will select the data and lock the table for exclusive use by the current OleDbConnection, but I cannot find any way to release that exclusive lock without closing the entire connection, which I'm trying to avoid having to do.
I don't see a point opening a connection exclusively and then using an adapter to fill a table, after which you want to release lock. You don't need a connection in the first place, adapter opens and closes the connection as needed:
DataTable table = new DataTable();
new OleDbDataAdapter("SELECT * FROM tran",
#"Provider=vfpoledb;Data Source=J:\epdata;Deleted=off")
.Fill(table);

how to use mysqlconnection throughout the application

I am trying to have a MySQL connection open in the main form. However, O am having trouble trying use the connection in other forms.
How should I set it up so that I only need to open the connection once in the whole program, and use the same connection to get data from database.
Or should I have a new connection open in each form?
Thank you
It is better to use using statement with SQL connection as follow:
using (SqlConnection connection = new SqlConnection(connectionString))
{
//Your code goes here
}
and make the connection string in App.config file.
You don't want to just leave a connection open the whole time the app is running. It's better to create a single function that you can call repeatedly if your goal is to simplify code readability. The below example is as basic as it gets, but you'll need to do a bit more for stored procedures and Parameter objects not in a query string. All this will do is fill a datatable.
public DataTable RunQuery(string query)
{
//connectionString should come from your configuration or a constant that is a part of this class
DataTable dt = new DataTable();
using (SqlCommand cmd = new SqlConnection(connectionString))
{
cmd.CommandText = query;
cmd.Connection.Open();
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
sda.Fill(dt);
}
cmd.Connection.Close();
}
return dt;
}
Calling it is easy.
RunQuery("Select * from myData");
Basically, you have to open your MySqlConnection once, and then reuse your connection with using, or by checking it´s state. It is the same as every ADO.NET library. Using the usingstatement you have guarantee that the object will be disposed and all resources released.
This link has everithing you need about working with MySql: https://www.codeproject.com/Articles/43438/Connect-C-to-MySQL

How to execute a query which uses multiple database

I am developing an ASP.Net website. I have to execute a query which fetches data from two different database.
I have two SqlConnection objects for these connections.
I have both the connections open. But in SqlCommand object, I can specify just one SqlConnection object.
SqlConnection conn = new SqlConnection("Data Source=xxx;Initial Catalog=xxx1;User ID=web_writeonly;Password=aaa;Network Library=DBMSSOCN");
SqlConnection conn1 = new SqlConnection("Data Source=xxx;Initial Catalog=xxx2;User ID=randomUser;Password=bbb;Network Library=DBMSSOCN");
conn.open();
conn1.open();
SqlCommand cmdUserInfo = new SqlCommand("<query goes here>", conn);
cmdUserInfo.Parameters.Add("#ifa", SqlDbType.NVarChar).Value = ifacode;
SqlDataAdapter sdaUserInfo = new SqlDataAdapter(cmdUserInfo);
sdaUserInfo.Fill(dtSummaryTbl);
conn.Close();
conn1.Close();
When I execute this code snippet, I get an error "The SELECT permission was denied on the object '*', database 'xxx2', schema 'dbo'."
Please help me out in sorting this problem.
Thanks!
That error means that you don't have sufficient permissions... check what sql login your website is associated with and then the permissions on the table you're trying to select data from.
Also, on closer inspection, one of your usernames is "web_writeonly"... kind of a hint if you're trying to do a select!!! ;)
Assuming your databases are on the same server why can't you just put your SQL into a stored procedure on one of the databases. I am pretty sure you can then just use one connection object and execute your stored procedure which gets data from two databases.

Tutorial on connecting c# to SQL server

I want to be able to edit a table in a SQL server database using c#.
Can someone please show me a very simple tutorial on connecting to the DB and editing data in a table.
Thank you so much.
First step is to create a connection. connection needs a connection string. you can create your connection strings with a SqlConnectionStringBuilder.
SqlConnectionStringBuilder connBuilder = new SqlConnectionStringBuilder();
connBuilder.InitialCatalog = "DatabaseName";
connBuilder.DataSource = "ServerName";
connBuilder.IntegratedSecurity = true;
Then use that connection string to create your connection like so:
SqlConnection conn = new SqlConnection(connBuilder.ToString());
//Use adapter to have all commands in one object and much more functionalities
SqlDataAdapter adapter = new SqlDataAdapter("Select ID, Name, Address from myTable", conn);
adapter.InsertCommand.CommandText = "Insert into myTable (ID, Name, Address) values(1,'TJ', 'Iran')";
adapter.DeleteCommand.CommandText = "Delete From myTable Where (ID = 1)";
adapter.UpdateCommand.CommandText = "Update myTable Set Name = 'Dr TJ' Where (ID = 1)";
//DataSets are like arrays of tables
//fill your data in one of its tables
DataSet ds = new DataSet();
adapter.Fill(ds, "myTable"); //executes Select command and fill the result into tbl variable
//use binding source to bind your controls to the dataset
BindingSource myTableBindingSource = new BindingSource();
myTableBindingSource.DataSource = ds;
Then, so simple you can use AddNew() method in the binding source to Add new record and then save it with update method of your adapter:
adapter.Update(ds, "myTable");
Use this command to delete a record:
myTableBindingSource.RemoveCurrent();
adapter.Update(ds, "myTable");
The best way is to add a DataSet from Project->Add New Item menu and follow the wizard...
Assuming you're using Visual Studio as your IDE you could just use LINQ to SQL. It's a pretty simple way to interact with your database and it should be pretty quick to get going.
Using LINQ to SQL is a pretty simple walk through in getting it up and running.
Have a read of the MSDN tutorial on Creating Data Applications. You may be able to clarify your question, or find the answers you need.
There is info on editing the data in the app but you have to get connected and load it into your app first.
The only reason to do this in C# is if you want to automate it somehow or create an interface for non-technical users to interact with the database. You can use a GridView control with an SQL datasource to manipulate the data.
#kevin: if he's just learning, I think its probably simpler to have him use SQLCommand object (or SQLDataAdapter).

Categories

Resources