I can connect to MySQL database from my WinForms app fine. The question is once I am logged in how can I perform multiple select statements without having to login again?
MySqlConnection connection = new MySqlConnection(MyConString);
connection.Open();
MySqlCommand command = connection.CreateCommand();
MySqlDataReader Reader;
command.CommandText = "select id from user ";
Then I want to perform a select statement for another table without having to create connection again.
How do I dothis?
I can't seem to just do connection.CreateCommand.
As long as the queries are within the same block, you can use the same connection.. However, once closed, you need to re-open it.
using( YourConnectionObject )
{
... open connection ...
... create your sql querying object... and command
SQLCommand.Connection = YourConnectionObject;
Execute your Query
SQLCommand.CommandText = "a new sql-select statement";
Execute your NEW query while connection still open/active
SQLCommand.CommandText = "a third sql-select statement";
Execute your THIRD query while connection still open/active
... close your connection
}
However, in your application, you can have a single "connection" object like at the application level, or at a form level with the necessary login / connection settings stuff. Then, internally to each form, you can
Open
Run Query
Run Query
Run Query
Close
as needed.
I see you're using a DataReader. You can only have 1 DataReader open at a time per connection. using blocks come in handy for those:
using( var reader = myCommand.ExecuteReader() ) {
while (reader.Read()) {
// get values, do stuff
}
}// reader gets closed
You only hint at it in the code in your question (currently), but it's possible that is part of your problem. You haven't shown how you're using the DataReader, so I'm not certain. Just a possibility.
Related
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);
We have a C# application using ADO.NET and an SQL-Server with SNAPSHOT Transaction Isolation Level. This is 'as is' and unfortunately cannot be modified.
Now we need insert stuff on a linked server.
We execute the following code (reduced to illustrate the problem):
// Create a snapshot Transaction and close the connection
using (var con = new SqlConnection(myConStr))
{
con.BeginTransaction(TransactionLevel.Snapshot);
}
// do something with a linked server
using (var con = new SqlConnection(myConStr))
{
using (var cmd = con.CreateCommand()
{
cmd.CommandText = "insert into LinkedServer.SomeDb..Table ...";
cmd.ExecuteNonQuery();
}
}
We get can an exception when trying to insert something into the linked server
'Remote access is not supported for transaction isolation level "SNAPSHOT"'
I wonder why it is not possible: We open the connection, make sure it is disposed (clearing all transactions, I guess) and use a second connection for the linked server call.
Executing the stuff in SSMS using plain SQL seems to work.
What are we missing? Is there a proper way to do it?
Thanks for any hints in the right direction.
The secret to understand the problem is the 'connection pooling' which is done by ADO.NET in the Background. The real connection is actually set to SNAPSHOT.
In the second part of the sample code, that connection simply gets reused thus still being in 'snapshot mode'.
The solution is to explicitly set the transaction isolation Level to something else right after opening the Connection.
using (var con = new SqlConnection(myConStr))
{
using (var cmd = con.CreateCommand()
{
cmd.CommandText = "set transaction isolation Level read committed";
cmd.ExecuteNonQuery();
}
using (var cmd = con.CreateCommand()
{
cmd.CommandText = "insert into LinkedServer.SomeDb..Table ...";
cmd.ExecuteNonQuery();
}
}
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
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
I have a T-SQL script to create a Database. I need to create this database runtime. When the application is Running.
What Connection String do I use?
How do I connect to the server and Create the Database? I am connecting to the server as a Network user. I am not using User "sa" I have a user "DBCreator"
My application is in C#.
I have this Script in T-SQL:
USE [master]
GO
CREATE DATABASE [XYZ]
-- Table Creation Code etc.
You can have two connection strings. One for master database to issue the CREATE DATABASE ... statement and another one for database created.
// You can use replace windows authentication with any user credentials who has proper permissions.
using (SqlConnection connection = new SqlConnection(#"server=(local);database=master;Integrated Security=SSPI"))
{
connection.Open();
using (SqlCommand command = connection.CreateCommand())
{
command.CommandText = "CREATE DATABASE [XYZ]";
command.ExecuteNonQuery();
}
}
// Quering the XYZ database created
using (SqlConnection connection = new SqlConnection(#"server=(local);database=XYZ;Integrated Security=SSPI"))
{
connection.Open();
using (SqlCommand command = connection.CreateCommand())
{
command.CommandText = "select * from sys.objects";
...
}
}
You can use the SMO objects to do that. I don't think i should explain what is already explained in details in a very good tutorial here
Definitely use SMO its intended to do everything that SSMS can do, and more! it actually has a command called Database.Create(), follow this MSDN page