How do statements in SQL correlate with C# - c#

I have created a database and i have linked it with a Windows Form Application
in Visual Studio and it is written in Visual C#. I am curious to know whether or not the buttons that i have added in the windows form application will correspond with
the statements that are written in SQL .
Will I need to implement code in the backend of SQL or C# or just one of the two.

You could try using something called Entity Framework, which can be installed if you right-click the project name and choose to Manage NuGet packages.
This will set up a framework for you so that you don't have to write any C# code connecting your form with your database. It is some what easy to use because it creates Table Adapters which makes the connection from a table in your database to your code, an example would be:
var myTableAdapter = new myDatabase_TableAdapters.myTableTableAdapter();
System.Data.DataTable myDataTable = myTableAdapter.GetData();
Now you have the data from your table in the SQL database in a DataTable and you have your TableAdapter as a connection between the two.
Say you want to take input from your users, then for our example consider the data comes from your text boxes then you could do something like:
string vehicleRegNum = vehicleRegNumTextBox.Text,
make = makeTextBox.Text,
engineSize = engineSizeTextBox.Text,
dateReg = dateRegTextBox.Text,
rentPerDay = rentPerDayTextBox.Text;
bool avail = availCheckBox.Checked;
myTableAdapter.Insert(vehicleRegNum, make, engineSize, dateReg, rentPerDay, avail);
This .Insert will add this data to your database (Here I am assuming all the text boxes go to one table in your database and that the order is as I have given them).
So in general,
Get Entity Framework setup in NuGet
Setup a table adapter from a table in your database
Update it with user input
A side note: I always like to add a user and date column to these kinds of tables so you can use:
string usr = System.Environment.UserName
var entryDate = System.DateTime.Now;
Clarification: It was pointed out to me by #DanRayson in the comments that I should be more clear about myDatabase_TableAdapters. It is not exactly a TableAdapter, it is however a TableAdapter which EntityFramework creates in the background for the user.

Related

Check for existence of a certain table in access DB using C# OleDB connection

I'm struggling to find a valid answer to what I'm trying to find.
Basically, I want to check if for example:
"tableNO1" exists or if every other table exists...
By the way, I'm using Access 2002-2003 if that somehow helps :)
Do you think I should upgrade to the latest version?
Background:
I'm trying to create run-time buttons that each one of them has a DB table, and when I close my program the tables that I created for each run-time created button will be saved. After I launch the program again I should click a button that will add these buttons that have DB tables (Each one of them has a dedicated table). for example, if 9 run-time buttons were created in the program before - each of them will have a DB table. I will have a max 9 button and each of them will be named tableNO(n) n=number of table
when I click the button that creates run-time buttons for the first time, it will create a button called "tableNO1", the second time "tableNO2" will be created, and so on...
Thanks in advance.
Ok, there are several ways to do this, but I suggest this code:
public Boolean TableExist(string sTable)
{
using (OleDbConnection conn = new OleDbConnection(Properties.Settings.Default.AccessDB2))
{
conn.Open();
string[] sRestrict = new string[] {null,null,null,null};
sRestrict[2] = sTable;
DataTable MySchema = new DataTable();
MySchema = conn.GetSchema("Columns",sRestrict);
return (MySchema.Rows.Count > 0);
}
}
The above is also how you can get the schema (table def) as a table.
Thus, say
if (TableExist("tblHotels")
{
// your code here
}
Now, because you are possible (likely) using a loop, then you might consider for reasons of performance to pass a valid connection to the TableExist function, and thus for your loop not re-create a connection each time - as that will slow things down quite a bit.
Note that "many" often suggest doing this:
SELECT * FROM MSysObjects WHERE [Name] = 'tableNO1' AND Type = 1
The problem with above is by default, the MySysObjects requires elevated rights. The database can be opened, and then using security settings in access the rights to MySysOjbects can be changed - but it more work then the above code/function.

Save Changes in DataGridView C#

After calling the table from the database into the dataGridView and entering data into the empty cells of this DataGridView, I want to save this data to my database by clicking on the button, but I don’t know how to do this
This is how I access db:
public MySqlConnection mycon;
public MySqlCommand mycom;
public string connect = "Server=localhost;Database=base;Uid=root;password=pas;charset=utf8";
public SD.DataSet ds;
mycon = new MySqlConnection(connect);
mycon.Open();
MySqlDataAdapter ms_data = new MySqlDataAdapter(script, connect);
SD.DataTable table = new SD.DataTable();
ms_data.Fill(table);
dataGridView1.DataSource = table;
mycon.Close();
Pains me to write it, but this should be the minimum set of calls necessary:
MySqlDataAdapter ms_data = new MySqlDataAdapter(script, connect);
new MySqlCommandBuilder(ms_data);
ms_data.Update(dataGridView1.DataSource as DataTable);
You need an adapter, and then passing it to a command builder should make the CB read the select command loaded into the adapter and use it to populate the adapter's other commands (insert/update/delete), then you can call Update and pass a modified table and the rows in the table will be examined to see if they're new, modified or deleted and the appropriate command will be called to persist the changes
script needs to be an SQL that selects the primary key columns from the DB
Why "pains to say it" ? Because it's such a long winded, hard work way of doing database access compared to even the technology that replaced it, let alone something modern like EF. If you're liking working with datatables, consider:
Add a new DataSet type of file to the project
Open it, right click the surface, add a tableadapter
Configure the connection string
Configure a "select that returns rows" query like SELECT * FROM sometable WHERE id = #someId
A tableadapter and datatable pair appear, that mimick the table in the database
Switch to a form, open the data sources window (View Menu, Other Windows), drag the table to the form - a datagridview, dataset, tableadapter, navigator etc appear.
Everything is wired up to go.
Your tableadapter is a dataadapter on steroids, and will Fill/Update the datatable from/to database. The datatable has named columns and is generally much nicer to work with. All the code for loading and saving is already written into the FormX.cs so you can take a look, but it basically amounts to:
var x = new BlahBlahTableAdapter();
x.FillBy(this.BlahBlahDataSet, someIdTextBox.Text);
Filling the datatable that is binded to the grid will cause the data to appear in the grid automatically.
Saving is similarly simple:
var x = new BlahBlahTableAdapter();
x.Update(this.BlahBlahDataSet);
Footnote: I believe you need MySQL Tools For Visual Studio installed for this to play nice. Also, you might encounter issues if you made a NetCore/Net5+ WinForms project because some elements of new .NET don't support winforms properly
Footnote2: See https://bugs.mysql.com/bug.php?id=99199 if you're wondering why the tableadapter wizard option "Refresh the dataset" is not working
If you want to try something more modern, there are lots of good EF tutorials out there. EF is a tool that uses a database to create objects in your code. The data for the objects lives in the database and is automatically transported back and forth from/to objects/database by EF. If you get into it, EF Core Power Tools is a very useful VS addin to have

Updating multiple values to sql table using Datagridview in C#

I am having a SQL table cost(sno,comp_name,sellingprice).
I need to develop an interface for entering values of sellingprice, where sno and comp_name are static values.
I set default value for sellingprice as 1.
For this purpose I used a Datagridview by choosing datasource and then the COST table contents to be displayed in the Datagridview.
Finally if user enters/updates values in the sellingprice column, then the changes need to be reflected in the Database.
Can somebody please help me in achieving this..
Thanks in advance..!
There are many ways to achieve what you're asking for. The easiest way is using SqlDataAdapter class.
There are at least 2 known to me ways to create Update/Insert/.. commands:
automatic (Adapater generates SQL itself)
manual (You do it in a way you like it)
For concrete and complete example of different patterns for this object look on
How To Update a SQL Server Database by Using the SqlDataAdapter Object in Visual C# .NET

Access to MS Access with C#

I've to retrieve information of an existing system which is using MS Access( :'( ).
So I added an existing Item(the mdb) to the project, and it created me a DataSet corresponding to all tables I've.
Once I've done this, I try to access to these data:
ClsDataSet dataSet = new ClsDataSet();
foreach (ClsDataSet.DOCDOCUMENTSRow docdocumentsRow in dataSet.DOCDOCUMENTS)
{
System.Console.WriteLine(docdocumentsRow.nom_document+"-->"+docdocumentsRow.nom_fichier);
}
System.Console.ReadLine();
Only to test...
But it doesn't enter in the foreach, it seems it thinks that the table is empty? I directly step on the ReadLine();
So did I missed something? I don't have any exception..
Should I load the table or something like this?
Thank you!
In the snippet you have posted there isn't any TableAdapter that fills your schemas in the dataset you have created. DataSet is just a representation of what you have on db-side, so it is only a structure of db tables and doesn't directly contain data.
To fill your schema with database records you have to call Fill method of the associated TableAdapter. Usually it is created automatically by Visual Studio Designer when you drag-n-drop some database table in a DataSet schema (.xsd).
Just creating the data set using the constructor does not yet retrieve the data. You need code to fill (=> select the rows from the MDB file and store them within your data set instance) the data set first.
The easiest would be to create an ODBC connection to the MDB file and use OdbcConnection and respective OdbsCommand instances to create the actual connection and "SELECT" statements.
EDIT
You may be able to connect to the MDB file directly using the Table Adapter designer. You would then not need to create an ODBC connection.
Here is a tutorial about connecting to an Access DB - http://www.homeandlearn.co.uk/csharp/csharp_s12p4.html. There is a link at the bottom to another page on that site on how to retrieve data.

How do I populate my VS2008 Data Sources window with a LINQ query table?

I´m (professionally) creating a SQL Server database client by using Visual Studio 2008, C# -> Windows Form(s). And I´m using all the built in stuff, provided by my friend VS Studio, dragging and dropping, creating SQL query tables in DataSet.xsd, and so on... I like that.
But!
I would like to try out LINQ, as I would like to have something that to me is more intuitive than pure SQL...
And (here comes the newbie-problem to be solved)!
I don´t know where to put the LINQ code to make a table "pop up" in the Data Sources window - meaning I´m completely stuck! How should I do it?
In the VS2008 menu,
Project > Add New Item… > Data (category) > LINQ to SQL Classes
A designer will open up.
Open your database in the Server Explorer pane, and drag you tables onto the design surface.
Edit after comments
Here is an example of using LINQ to query the database in code:
using(var db as NameOfYourLinqDataContextClass)
{
var myCars = from car in db.cars
where car.owner_name.Equals("Jay")
select car;
foreach (var car in myCars)
{
myForm.myCarsList.Add(string.Format("{0} {1}", car.make, car.model));
}
}
Here I've queried the cars table in my database for any row where the value in the car_owner column is "Jay." Using this query, I concatenate the values from the make and model columns and put them in a list or something on my form.
LINQ-to-SQL creates CLR classes based on the schema of your database. You create these query expressions "on-the-fly," which get converted into T-SQL queries behind the scenes and are executed against the database when the results are needed. That is to say that in the example above, no call is made to the database until the line foreach (var car in myCars).

Categories

Resources