c# : one class to connect to sql server - c#

Hello there I hope you're having a great time.
I have a question And I will break it down into 3 points:
1: create a class to connect to sql server the connection should be made using sql server authentication.
This class should contain several variables for connection parameters.
2: create a user form that shows the current connection parameters. And allow the user to update those parameters. In this form there should be a button to test the connect and another button to save the user changes to the connection parameters.
3: how to share the connection, created by the class we made in point 1, between different forms in the application. Without keeping too many open connections ideally only one connection should be open.
I will add the code that can solve this problem I hope that you can help me refine it.
I am new to all of this.
Thank you all for help.

already exists; SqlConnection and maybe SqlConnectionStringBuilder
that kinda already exists, via the IDE, but last time I checked this was not a redistributable dll. You could, however, simply hook a SqlConnectionStringBuilder to a PropertyGrid - or just write the UI from scratch
even "only one connection should be open" is wrong, IMO - let the inbuilt connection pooling deal with that; all you need is some configuration class with the connection string - and just deal with the connections as you need them, very locally - i.e.
using(var conn = new SqlConnection(Config.ConnectionString))
{
conn.Open();
// NOT SHOWN: do a couple of related operations
} // <== and here, it dies

1 : go to MSDN website you'll find what you need :
http://msdn.microsoft.com/fr-fr/library/system.data.sqlclient.sqlcommand.aspx?cs-save-lang=1&cs-lang=csharp#code-snippet-2
private static void ReadOrderData(string connectionString)
{
string queryString =
"SELECT OrderID, CustomerID FROM dbo.Orders;";
using (SqlConnection connection = new SqlConnection(
connectionString))
{
SqlCommand command = new SqlCommand(
queryString, connection);
connection.Open();
SqlDataReader reader = command.ExecuteReader();
try
{
while (reader.Read())
{
Console.WriteLine(String.Format("{0}, {1}",
reader[0], reader[1]));
}
}
finally
{
// Always call Close when done reading.
reader.Close();
}
}
}
2: look at your connection properties (http://msdn.microsoft.com/en-us/library/System.Data.SqlClient.SqlConnection_properties.aspx) and fill a listView or equivalent with it
3: Use previous SqlConnection.Open() to deal with it

Related

sql Dependency detect changes of records and send message to clients

I am trying to use sql Dependency to check that a table data has been changed by other clients I followed the turotial here but when I try to create the queue i get the following error message this is my c# code and sql statement.
Edit 1
Sorry I forgot to include the tutorial in my first post here is the link in the tutorial it states quename but does not say how to ccreate it.
https://learn.microsoft.com/en-us/dotnet/framework/data/adonet/sql/detecting-changes-with-sqldependency
CREATE QUEUE ExportedOrdersChangeMessage CREATE SERVICE
ExportedOrdersService ON QUEUE ExportedOrdersChangeMessage
([http://schemas.microsoft.com/SQL/Notification/PostQueryNotification])
The error I receive after running the above is the following.
Msg 15151, Level 16, State 1, Line 5
c'http://schemas.microsoft.com/SQL/Notification/PostQueryNotification',
because it does not exist or you do not have permission.
Basically what I want to be able to do is if a user is atempting to change a record I want to send a notification to the other clients. Is this the best method for this approach its a winforms business app if any other libarys that make this easier would be great.
I am using sql Server 2017 express which I asumes would have this as standard?.
private void DetectChanges()
{
// Assume connection is an open SqlConnection.
string connectionString = ConfigurationManager.AppSettings["ConnectionString"];
using (SqlConnection con = new SqlConnection(connectionString))
{
// Create a new SqlCommand object.
using (SqlCommand command = new SqlCommand("SELECT exportedtoMeteor FROM dbo.exported", con))
{
// Create a dependency and associate it with the SqlCommand.
SqlDependency dependency = new SqlDependency(command);
// Maintain the reference in a class member.
SqlDependency.Start(connectionString, "ExportedOrdersChangeMessage");
// Subscribe to the SqlDependency event.
dependency.OnChange += new
OnChangeEventHandler(OnDependencyChange);
// Execute the command.
using (SqlDataReader reader = command.ExecuteReader())
{
// Process the DataReader.
}
}
}
}
// Handler method
void OnDependencyChange(object sender, SqlNotificationEventArgs e)
{
// Handle the event (for example, invalidate this cache entry).
}
void Termination()
{
string connectionString = ConfigurationManager.AppSettings["ConnectionString"];
// Release the dependency.
SqlDependency.Stop(connectionString, ExportedHacket);
}
I don't know the answer to your direct question but Butterfly Server .NET detects changes to databases (MySQL, Postgres, SQLite, MS SQL Server, etc) and allows creating Dynamic Views based on SELECT statements that publish events if the SELECT results change. There are caveats (like all database operations have to be performed via the IDatabase interface provided by Butterfly Server .NET). However, it's similar enough to what you are doing that you may be interested.

c# sqlite database locked when inserting

I am using SQLite in a C#
I have an insert query in a win form that works but on another win form that doesn't. when I have read about the issue it says it might be because there is an open connection somewhere but I have checked it all and even used SQLiteConnection.ClearAllPools(); after every close. now the 1st winform have only 1 open / close, the other one has 3.
I have tried the query using SQLite Browser to make sure it wasn't an issue with the query and it worked successfully. now when I debugged the issue occurs when this line executes cmd.ExecuteNonQuery(); that, of course, executes the query (insert into ....). so I tried changing the type of the table primary key (from varchar to integer). and I still have the issue. below is a sum of how it is.
myconnection = new SQLiteConnection(connectionString);
myconnection.Open();
//select stuff here
//verifications here
//insert inside verification
//finally { myconnection.close(); }
Did you try wrapping your connection in a using statement?
using(var myconnection = new SQLiteConnection(connectionString))
{
myconnection.Open();
//Your code here
}
This will call Dispose method of the connection regardless of execution path, which could possibly be doing more than just closing the connection.
Be aware to click on Write changes on SQLite browser,
if it is running and there are any unsaved changes!
In my case it was very stupid of me, I was making changes in the SQLite browser and did not click on write changes, which locked the DB to be modified by the services. After I clicked the Write changes button, all the post requests worked as expected.
According to #Rohan Shenoy in this topic: SQLite Database Locked exception
may be you should also try this
using (var con = new SQLiteConnection { ConnectionString = "connectionstring" })
{
using(var cmd = new SQLiteCommand { Connection = con })
{
// check state connection if open then close, else close proceed
if(con.State == ConnectionState.Open)
con.Close();
//then
try
{
// try connection to Open
con.Open();
}
catch
{
//catch if found error, message : 'Invalid Connection string'
}
........ // insert query here
} // Close Command
} // Close Connection

Update table (rows) Access 2007 and C# 2010

So this is probably the most naive question but that is what questions are for I guess;
Then, my issue is that I have no idea on how to connect Visual C# Express 2010 to Access 2007 and do the typical insert, update, delete, search in an application in C#, I have just learned the basics (finished a console tutorial, which I believe is more than enought, having previous background of VB6 using access 97), and I have been searching here and in the web, but the only thing I could find where the msdn tutorials which I dind't find really clear.
So in my app I just need to link comboboxes, query those values to obtain new ones, do calculations and then store in arrays (and maybe show these in datagrids as well as edit them from said datagrids, which is a bit more complicated I guess) and finally store them in various tables, but I haven't really found a strong (or most likely simple) manual that will guide me to create the typical app insert, update, delete using winforms.
Do you guys have any good links in order to do this?
Thanks.
You can try with this code
Here link about string connection : http://www.connectionstrings.com/access-2007
var query = "...";
var connectionString = "...";
using (OleDbConnection connection = new OleDbConnection(connectionString))
{
// The insertSQL string contains a SQL statement that
// inserts a new row in the source table.
using(var command = new OleDbCommand(query))
{
// Set the Connection to the new OleDbConnection.
command.Connection = connection;
// Open the connection and execute the insert command.
try
{
connection.Open();
command.ExecuteNonQuery();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
// The connection is automatically closed when the
// code exits the using block.
}
}

Connecting a MS Access (.mdb) Database to a MVC3 Web Application

Right, I have been tasked with developing a new application in MVC3 that unfortunately has to integrate very slightly with a classic asp web site. This won't be forever as the old site will get an update at some point, but not yet. In the mean time however the new MVC3 application will need a little bit of access to the database for the old site, which is a old MS Access .mdb whereas the new app will be using sql server 2008.
I would greatly appreciate it if someone could give me some examples of how to connect to the access db, aswell as how to execute sql queries (i am fine writing the sql, just got no idea how to execute against the database from my mvc3 app).
thanks in advance
EDIT: I've not got much experience with the old site, but it appears to use the JET adaptor if that helps! ;-)
Your question requires an answer too extensive to be given in detail
I will give you a check list of things and class to research
Define the connection string used to reach your database [see
here]
Create and open the OleDbConnection
Define your OleDbCommand and the command text to be executed
Create and use an OleDbDataReader to read your data line by line
Create and use an OleDbDataAdapter to read your data and load a
DataSet or DataTable
Now don't forget to close your connection and use parametrized query
string connectionString = Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\mydatabase.mdb;Jet OLEDB:Database Password=MyDbPassword;
public void InsertRow(string connectionString, string insertSQL)
{
using (OleDbConnection connection = new OleDbConnection(connectionString))
{
// The insertSQL string contains a SQL statement that
// inserts a new row in the source table.
OleDbCommand command = new OleDbCommand(insertSQL);
// Set the Connection to the new OleDbConnection.
command.Connection = connection;
// Open the connection and execute the insert command.
try
{
connection.Open();
command.ExecuteNonQuery();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
// The connection is automatically closed when the
// code exits the using block.
}
}

Managing SQL Server Connections

What is the the best practice for SQL connections?
Currently I am using the following:
using (SqlConnection sqlConn = new SqlConnection(CONNECTIONSTRING))
{
sqlConn.Open();
// DB CODE GOES HERE
}
I have read that this is a very effective way of doing SQL connections. By default the SQL pooling is active, so how I understand it is that when the using code ends the SqlConnection object is closed and disposed but the actual connection to the DB is put in the SQL connection pool. Am i wrong about this?
That's most of it. Some additional points to consider:
Where do you get your connection string? You don't want that hard-coded all over the place and you may need to secure it.
You often have other objects to create as well before your really use the connection (SqlCommand, SqlParameter, DataSet, SqlDataAdapter), and you want to wait as long as possible to open the connection. The full pattern needs to account for that.
You want to make sure your database access is forced into it's own data layer class or assembly. So a common thing to do is express this as a private function call:
.
private static string connectionString = "load from encrypted config file";
private SqlConnection getConnection()
{
return new SqlConnection(connectionString);
}
And then write your sample like this:
using (SqlConnection sqlConn = getConnection())
{
// create command and add parameters
// open the connection
sqlConn.Open();
// run the command
}
That sample can only exist in your data access class. An alternative is to mark it internal and spread the data layer over an entire assembly. The main thing is that a clean separation of your database code is strictly enforced.
A real implementation might look like this:
public IEnumerable<IDataRecord> GetSomeData(string filter)
{
string sql = "SELECT * FROM [SomeTable] WHERE [SomeColumn] LIKE #Filter + '%'";
using (SqlConnection cn = getConnection())
using (SqlCommand cmd = new SqlCommand(sql, cn))
{
cmd.Parameters.Add("#Filter", SqlDbType.NVarChar, 255).Value = filter;
cn.Open();
using (IDataReader rdr = cmd.ExecuteReader())
{
while (rdr.Read())
{
yield return (IDataRecord)rdr;
}
}
}
}
Notice that I was also able to "stack" the creation of the cn and cmd objects, and thus reduce nesting and only create one scope block.
Finally, a word of caution about using the yield return code in this specific sample. If you call the method and don't complete your DataBinding or other use right away it could hold the connection open for a long time. An example of this is using it to set a data source in the Load event of an ASP.NET page. Since the actual data binding event won't occur until later you could hold the connection open much longer than needed.
Microsoft's Patterns and Practices libraries are an excellent approach to handling database connectivity. The libraries encapsulate most of the mechanisms involved with opening a connection, which in turn will make your life easier.
Your understanding of using is correct, and that method of usage is the recommended way of doing so. You can also call close in your code as well.
Also : Open late, close early.
Don't open the connection until there are no more steps left before calling the database. And close the connection as soon as you're done.

Categories

Resources