Tutorial on connecting c# to SQL server - c#

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).

Related

Create dinamically a Dataset to fill reports on Visual Studio

I am searching for a way to create dinamic Datasets to be binded to my reports
(I am using C# on Visual Studio 2015 Community).
Can anyone explain how can I do it?
The first idea is to create a Dataset from a query then bind it to my report,
but I cannot create a report without telling VS a DataSet (which must be connected to a DB using a static ConnectionString (VS purposes me only the Wizard, I have no idea on how to do it dinamically)
Example Code of what I would like to have:
DataSet myReportDS = ADO.getDS("SELECT * FROM" +
"Table1 JOIN Table2 ON Table1.pkey = Table2.fkey");
//here I am stuck because I don't know even how to add objects without a
//static connection to my report (Designer) and how to bind it.
Have also in mind that the DBMS is PostgreSQL.
Thanks a lot.
In the end I found this article to solve my problem
https://blogs.msdn.microsoft.com/magreer/2008/10/16/setting-the-datasource-for-a-report-at-runtime/
The problem in fact is that VS forces the user to have a static DataSet to permit the report creation. So basically I had to create a copy of my DB Schema in local environment, then I executed my queries normally and then used Report.Fill() method. As soon as the schema is the same it works!
You could use a SqlDataAdapter or OleDbDataAdapter.
For example:
// Assumes that connection is a valid SqlConnection object.
string queryString =
"SELECT CustomerID, CompanyName FROM dbo.Customers";
SqlDataAdapter adapter = new SqlDataAdapter(queryString, connection);
DataSet customers = new DataSet();
adapter.Fill(customers, "Customers");
There are more examples on the msdn site.
Source: https://msdn.microsoft.com/en-us/library/bh8kx08z(v=vs.110).aspx

How to copy a populated MYSQL-Table to another Database in C#

I am using C#, .net 3.5 and a MySQL-Database. I have a populated table on Server 1 which I want to copy to Server 2. On Server 2 I have the same table structure, but the table is empty. Now I want to copy the data from Server 1 to Server 2.
I connect to Server 1 and fill the information into a DataSet - no problem. Then I open a second connection to the other server. My problem is, how can I store this DataSet on the second Server? The Update()-command has no effect, even if I set the same UpdateCommand und InsertCommand-CommandText as for Server 1. I get no error when I use Update(DataSet,"TableName"), but the table is still empty.
For MSSQL-Databases BulkCopy would be an option, but it seems that there is no equivalent for MySQL DBs!?
I do not want to use mysqldump, I want to do it programmaticaly in C# on a client.
Any idea?
EDIT:
MySqlConnection conn_DB1 = new MySqlConnection(connString_DB1);
MySqlDataAdapter adp_DB1 = new MySqlDataAdapter("select * from myDB", conn_DB1);
DataSet theDataSet_DB1 = new DataSet();
adp_DB1.Fill(theDataSet_DB1, "myDB"); //everything is fine, the Data is there
MySqlConnection conn_DB2 = new MySqlConnection(connString_DB2);
MySqlDataAdapter adp_DB2 = new MySqlDataAdapter("select * from myDB", conn_DB2);
DataSet theDataSet_DB2 = new DataSet();
adp_DB1.Fill(theDataSet_DB2, "myDB"); //this DataSet is empty, of course
theDataSet_DB2 = theDataSet_DB2.Copy(); //the data is updated, the second DataSet has all the rows as expected
adp_DB2.Update(theDataSet_DB2, "myDB"); //no error on execution, but the table is still empty on the second server
The rows in theDataSet_DB2.Tables are "unchanged", so any occurs. You must mark rows as "added" before to update them.
foreach (DataTable table in theDataSet_DB2.Tables)
foreach (DataRow row in table.Rows)
row.SetAdded ();
It's necessary to build a MySqlCommandBuilder associated to the dataAdapter:
new MySqlCommandBuilder (dataAdapter);
I am not sure which library you use to access MySQL DB...
For a "pure ADO.NET" with the original ADO.NET provider from MySQL see this artcile http://www.codeproject.com/KB/database/GenericCopyTableDataFcn.aspx
IF you use the MySQL .NET connector there is a class called MySqlBulkLoader see http://dev.mysql.com/doc/refman/5.1/en/connector-net-programming-bulk-loader.html . this class takes AFAIK a file - so would have to create a file from the source table first to use it...
IF you are using the Devart MySQL components you could:
MySqlLoader ML = new MySqlLoader("myDB", conn_DB2);
ML.CreateColumns();
ML.LoadTable(theDataSet_DB1.Tables[0]);

Update database using SqlCeDataAdaptor

I populate a listview from a Dataset that accesses sqlserver in visual studio 2008 express edition. I've been trying to update the listview and database simultaneously.
SettingTxt.Text references a textbox
With the following code, I've been able to update the list view with the information entered into the textbox, but the same update is not performed in the database. If anyone can help me resolve this, I would greatly appreciate it. I know there are alot of forums online regarding this exact problem, but I can't seem to get it working.
thisConnection = new SqlCeConnection("Data Source=AugMedDB.sdf;Password=");
thisConnection.Open();
SqlCeCommand cmd = thisConnection.CreateCommand();
cmd.CommandText = "UPDATE Patient SET Setting = \'" + SettingTxt.Text + "\' WHERE (PtID=0) AND (EquipID=1) AND (Control='Lever')" ;
SqlCeDataAdapter adp = new SqlCeDataAdapter();
adp.UpdateCommand = cmd;
dataSet.Tables[0].Rows[0][2] = SettingTxt.Text;
adp.Update(dataSet);
Thanks in advance.
Moved from an answer:
What I currently have is:
SqlCeCommand cmd = thisConnection.CreateCommand();
cmd.CommandText = "SELECT column FROM table WHERE id=0";
SqlCeDataAdapter adp = new SqlCeDataAdapter(cmd);
adp.SelectCommand = cmd;
DataSet ds = new DataSet();
ds = dataS.getDataSet();
adp.Fill(ds, "Patient");
SqlCeCommand comm = thisConnection.CreateCommand();
comm.CommandText = "UPDATE table SET Setting = 'value' WHERE (PtID=0)";
adp.UpdateCommand = comm;
adp.Update(ds, "Patient");
And I'm not understanding all the tutorials I find. Thanks in advance.
Update:
Yet even something as simple as the following doesn't update the database:
SqlCeConnection thisConn = new SqlCeConnection("Data Source=AugMedDB.sdf;Password=");
String query = "UPDATE Patient SET Setting = 'TopyTruck' WHERE (PtID=0) AND (EquipID=1) AND (Control='Lever')";
thisConn.Open();
SqlCeCommand commd = new SqlCeCommand(query, thisConn);
commd.ExecuteNonQuery();
thisConn.Close();
Your UPDATE statement is not suitable for an Adapter.Update(), for that it needs parameters and must be aligned with the SELECT statement.
You could try to execute that Command directly (w/o the adapter) or create a better update statement (using the dataset designer ).
Update
After filling the dataset,
generate the other SQL statements with a CommandBuilder (I think it exists for SqlCe)
or use your use your own Update command without the adapter. Just call comm.ExecuteNonQuery()
Tip 1: It may help to create a temporary (WinForms) project and use the VS tools to "Add a Datasource". You can look in the Dataset designer how VS generates the commands etc.
Tip 2: There are other options available, like entity framework. Datasets are (becoming) an "end of life" tech.
Thank you so much for all your help. I actually found the source of the problem. I had multiple references to the database; one within my project and another copy in bin/debug. I was correctly updating the copy in bin/debug but I was looking at the copy in my project. Once I deleted all copies, other than the one in bin/debug, it all worked and made sense. Now I see the updates in the database in bin/debug/

Storing SQL Tables for use in visual studio

I'm trying to create a windows form application that manipulates data from several tables stored on a SQL server.
What's the best way to store the data locally, while the application is running? I had a previous program that only modified one table, and that was set up to use a datagridview. However, as I don't necessarily want to view all the tables, I am looking for another way to store the data retrieved by the SELECT * FROM ... query.
Is it better to load the tables, make changes within the C# application, and then update the modified tables at the end, or simply perform all operations on the database, remotely (retrieving the tables each time they are needed)?
You can take in one table at a time using a ConnectionString and assign it to a DataTable. You can then make changes to the DataTable in any form you want. Once you are finished making the changes you can commit the changes back to Database by using a DataAdapter.
Here's how to get a table:
DataTable table;
using (SqlDbConnection connection = new SqlDbConnection(connectionString))
{
connection.Open();
using (SqlDbCommand command = new SqlDbCommand(tableName, connection))
{
command.CommandType = CommandType.TableDirect;
SqlDbDataReader dr = command.ExecuteReader(CommandBehavior.CloseConnection);
table = new DataTable(tableName);
routeID.Load(dr);
}
}
Here's how to commit the table after changes, make sure to assign your DataTable to a DataSet in order to get the changes for commit:
DataSet dataSet = new DataSet();
dataSet.add(table);
using (var adapter = new SqlDbDataAdapter("SELECT * FROM " + tableName, connection))
{
using (var builder = new SqlDbCommandBuilder(adapter))
{
adapter.Fill(dataSet, tableName);
using (DataSet newSet = dataSet.GetChanges(DataRowState.Added))
{
builder.QuotePrefix = "[";
builder.QuoteSuffix = "]";
adapter.InsertCommand = builder.GetInsertCommand();
adapter.Update(newSet, tableName);
}
}
}
There may be a few miss Types, I didn't compile to check for Errors. Good Luck.
The DataSet object has methods that give you the ability to manipulate data from multiple tables in memory, and then save those changes back to the database. Whether that's a good idea depends on your requirements and data--are there multiple simultaneous users, how do you need to handle conflicting updates, etc. I usually prefer to write changes back to the DB immediately, but then, I usually work in a web app context.

Getting a DataSet from an SQL Express Server C#

How can I get a DataSet with all the data from a SQL Express server using C#?
Thanks
edit: To clarify, I do want all the data from every table. The reason for this, is that it is a relatively small database. Previously I'd been storing all three tables in an XML file using DataSet's abilities. However, I want to migrate it to a database.
You can use the GetSchema method to get all the tables in the database and then use a data adapter to fill a dataset. Something like this (I don't know if it compiles, I just paste some code and change it a bit):
DbProviderFactory factory = DbProviderFactories.GetFactory("System.Data.SqlClient");
DataTable tables = null;
DataSet database = new DataSet();
using (DbConnection connection = factory.CreateConnection())
{
connection.ConnectionString = "Data Source=(local);Initial Catalog=Northwind;Integrated Security=True";
string[] restrictions = new string[4];
// Catalog
restrictions[0] = "Northwind";
// Owner
restrictions[1] = "dbo";
// Table - We want all, so null
restrictions[2] = null;
// Table Type - Only tables and not views
restrictions[3] = "BASE TABLE";
connection.Open();
// Here is my list of tables
tables = connection.GetSchema("Tables", restrictions);
// fill the dataset with the table data
foreach (DataRow table in tables.Rows)
{
string tableName = table["TABLE_NAME"].ToString();
DbDataAdapter adapter = factory.CreateDataAdapter();
DbCommand command = factory.CreateCommand();
command.Connection = connection;
command.CommandType = CommandType.Text;
command.CommandText = "select * from [" + tableName + "]";
adapter.SelectCommand = command;
adapter.Fill(database, tableName);
}
}
EDIT:
Now I refactored it a bit and now it's working as it should. The use of DbConnection and DbProviderFactories is for database engine abstraction, I recommend using it so you can change the database engine changing this line and the connection string:
DbProviderFactory factory = DbProviderFactories.GetFactory("System.Data.OracleClient");
The GetSchema method will retrive all tables from your database to a DataTable and then we get all the data from each table to the DataSet using the DataAdapter.
I think you need to narrow down the question somewhat... All the data? You mean, all the data in every table in every database? Well, the only answer to that is, a lot of code.
To connect to and talk to a SQL Server Express database engine, use the classes in the System.Data.SqlClient namespace, namely:
SqlConnection: Connect to the database
SqlCommand: Talk to the database
SqlDataReader: Iterate over data retrieved from the database
You can check the MSDN pages for all of these classes by clicking on the links above.
Here are some overview-links with more information:
CodeProject: Beginners guide to accessing SQL Server through C#
DevHood: Accessing SQL Server Data in C# with ADO.NET
Note that by and large, you use a SQL Server Express database engine the same way as the full SQL Server product, the difference is more in the tools you get with it, and some limitations in the express engine. Other than that you can just use the classes and language that you would use for a normal SQL Server database engine installation.
If this post didn't answer your question, please elaborate, and you have a higher chance of getting the answer you seek.
This can be done by using dataAdapter class.

Categories

Resources