Reconnect SqlDataAdapter - sqldataadapter

I have this code
DataTable dt= new DataTable();
SqlDataAdapter da;
private void LoadData()
{
using (SqlConnection cnn = new SqlConnection(ConfigurationManager.ConnectionStrings["cnn"].ConnectionString))
{
da = new SqlDataAdapter("Select * from table",cnn);
da.Fill(dt);
}
}
The connection will be closed after, right?
If i want to update the DataTable, how can i reconnect da to cnn?

Yes, the using statement will call Dispose on the SqlConnection. See using Statement.
To reconnect in this fashion you'd need another using statement to do your update or update within the original using statement.

The Fill method retrieves rows from the data source using the SELECT statement specified by an associated SelectCommand property. The connection object associated with the SELECT statement must be valid, but it does not need to be open. If the connection is closed before Fill is called, it is opened to retrieve data, then closed. If the connection is open before Fill is called, it remains open.
Source:See this

Related

Updating Database Value in windows forms

I am trying to do a function to update a value in a SQL database, this is my table
This is the function
private void UpdateGanToDB(float entrada, string Id)
{
string string_entrada = entrada.ToString();
string conString = Properties.Settings.Default.LocalDataBaseConnectionString;
string command_string = "UPDATE Gan SET Ganan = #GetGan WHERE Id = #GetId";
SqlConnection connection = new SqlConnection(conString);
SqlCommand cmd = new SqlCommand(command_string, connection);
cmd.Parameters.AddWithValue("#GetGan", string_entrada);
cmd.Parameters.AddWithValue("#GetId", Id);
try
{
connection.Open();
int row = cmd.ExecuteNonQuery();
if (row > 0) {
MessageBox.Show("Upgrade successful");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
connection.Close();
}
}
I am getting the message "upgrade successful" but when I check the database I can't see the changes. When I run the text in the command_string with known values I can see the changes but not with my function
Edit:
I added this code to the code above
int row = cmd.ExecuteNonQuery();
if (row > 0) {
SqlCommand command = new SqlCommand("SELECT * FROM Gan ", connection);
SqlDataAdapter adapter = new SqlDataAdapter(command);
System.Data.DataTable dataTable = new System.Data.DataTable();
adapter.Fill(dataTable);
MessageBox.Show(dataTable.Rows[0]["Ganan"].ToString());
}
To see if it is updating the value and I get the excepted 200 (Original value was 0) But When I close the application and see the values in the local database I see the original value 0 I don't know why the update is not saving
EDIT2:
I found another post with a work around for this problem: Can I commit changes to actual database while debugging C# in Visual Studio?
I think your code is correct and there is no problem
If you created database via Add\NewItem\Service-Base Database
I'm not sure, but I think After running your project, one copy of your original database will be included in the debug folder in your project and the update operation and also other operations run on that, not your original database
so, if you want to see a result, you should connect to that via View\ServerExplorer
meantime, after Change your Code and rebuild your Project, your debug database will be deleted and again one copy of your original database will be included in the debug folder

C#, SQL Server database, connection timeout. The timeout period elapsed prior to obtaining a connection from the pool

I am using a connection class for my connection and then I call the class for connecting.
After I use the connection several times it freezes and then gives a error. It seems I have got to many connections open at the same time I can't figure out how tho close the open connections. If that is the real problem.
MyConnection class:
public class MyConnection
{
private SqlConnection _con;
public SqlCommand Cmd;
private SqlDataAdapter _da;
private DataTable _dt;
public MyConnection()
{
_con = new SqlConnection("Data Source=192.168.1.12\\grs;Initial Catalog=BGI;Persist Security Info=True;User ID=awplanung;Password=pass");
_con.Open();
}
public void SqlQuery(string queryText)
{
Cmd = new SqlCommand(queryText, _con);
}
public DataTable QueryEx()
{
_da = new SqlDataAdapter(Cmd);
_dt = new DataTable();
_da.Fill(_dt);
return _dt;
}
public void NonQueryEx()
{
Cmd.ExecuteNonQuery();
}
}
And now I call this connection from my forms: like this one.
MyConnection con = new MyConnection();
con.SqlQuery("SELECT ARartikelnr ,ARartikelbezeich, ARartwarengruppe, ARanzahleinheiten, ARinhalteinheiten, ARanzgebindepal FROM BGARTIKEL where ARartikelnr BETWEEN '" + textBox2.Text + "' and '" + textBox3.Text + "' order by ARinhalteinheiten, ARartwarengruppe");
dt = con.QueryEx();
Each time I open a new form I make a
MyConnection con = new MyConnection();
and make many similar
con.SqlQuery("Select string")
After I open a second form it freezes when I do a new long select. What is strange is that I have used these 2 forms without problems, but in the first one I made a datagrid fill with a button. and now i changed if to fill directly from the form load. and when i go to the next form i cant fill my other datagrid on the new form giving that error.
Error:
Timeout expired. The timeout period elapsed prior to obtaining a connection from the pool. This may have occurred because all pooled connections were in use and max pool size was reached.
Make your MyConnection class disposable. And dispose it when you are done with data.
implement IDisposable interface on class
(public class MyConnection : IDisposable)
implement Dispose method where dispose your connection
public void Dispose()
{
_con.Dispose();
}
and use it like this
using(MyConnection con = new MyConnection())
{
con.SqlQuery("...");
dt = con.QueryEx();
}

Connection property has not been initialized Error (ExecuteNonQuery)

This question has been addressed all over the web and I tried a lot of things without success. The SQL EXPRESS service is setup to accept local system account but the problem still exists.
This is my connection string:
<add name="PhoneTemplateChange" providerName="System.Data.SqlClient" connectionString="Data Source=.\SQLEXPRESS;Database=PhoneTemplateChange;Integrated Security=SSPI" />
I created a class to do database operations in the constructor I have
_connectionString = System.Web.Configuration.WebConfigurationManager.ConnectionStrings["PhoneTemplateChange"].ConnectionString;
and a method in this class to insert data
public void AddNewChangeOrder(int operation, int targetExt)
{
using (SqlConnection con = new SqlConnection(_connectionString))
{
string sql = "INSERT into [dbo].ChangeOrder (operation, targetExt, dtrequested) VALUES (#operation, #targetExt, #dtrequested)";
using (SqlCommand cmd = new SqlCommand(sql))
{
try
{
cmd.Parameters.AddWithValue("#operation", operation);
cmd.Parameters.AddWithValue("#targetExt", targetExt);
cmd.Parameters.AddWithValue("dtrequested", DateTime.Now);
//con.CreateCommand();
con.Open();
//cmd.InitializeLifetimeService();
int rows = cmd.ExecuteNonQuery();
con.Close();
}
catch (SqlException e)
{
throw new Exception(e.Message);
}
}
}
I have played around with the connection string trying all different suggestions, also the commented code in the method above is what I tried to solve the problem. Still no luck!
I also changed the connection string I get two different exceptions this way
Database=PhoneTemplateChange
The above gives the exception in the title.
And the following gives the Exception "Cannot open Database PhoneTemplatechange.mdf requested by the login. Login failed for user 'mydomain\myusername'"
Database=PhoneTemplateChange.mdf
Any ideas?
You are missing the line of code where you specify that cmd uses con as it's connection. As a result the Command (cmd) has no connection, and con isn't associated with any command at all.
Add this line before executing:
cmd.Connection - con;
Alternatively (and better IMO) change your using statement as follows:
using (SqlCommand cmd = new SqlCommand(sql, con))

It's possible to use OleDbConnections with the Script Component?

I'm building an ssis package and I wish to use an existing OleDbConnection inside the Script Component. Here is my code:
public override void AcquireConnections(object Transaction)
{
base.AcquireConnections(Transaction);
cm = this.Connections.Connection;
con = (OleDbConnection)cm.AcquireConnection(Transaction);
MessageBox.Show(con.ToString());
}
When I close BIDS, i get the following message:
"System.InvalidCastException: Unable to cast COM object of type 'System.__ComObject' to class type 'System.Data.OleDb.OleDbConnection'. Instances of types that represent COM components cannot be cast to types that do not represent COM components; however they can be cast to interfaces as long as the underlying COM component supports QueryInterface calls for the IID of the interface."
The same code works fine with an Ado.Net connection. Can I use OleDbConnection here or Script Component only supports Ado.Net?
Thanks in advance.
As mentioned in the MSDN
You cannot call the AcquireConnection method of connection managers that return unmanaged objects, such as the OLE DB connection manager and the Excel connection manager, in the managed code of a Script task.
You need to use the ADO.NET connection manager if you want to use Aquire Connection method
in order to use OLEDB connection add a reference to Microsoft.SqlServer.DTSRuntimeWrap and try the below code
ConnectionManager cm = Dts.Connections["oledb"];
IDTSConnectionManagerDatabaseParameters100 cmParams =
cm.InnerObject as IDTSConnectionManagerDatabaseParameters100;
OleDbConnection conn = cmParams.GetConnectionForSchema() as OleDbConnection;
MSDN Link
Just in case someone googled this and couldn't find a real solution, you have to override the AcquireConnections, PreExceute and ReleaseConnections methods in order to use an OleDbConnection. The trick is the ConnectionString property:
OleDbConnection con;
OleDbCommand cmd;
IDTSConnectionManager100 connMgr;
/*Here you prepare the connection*/
public override void AcquireConnections(object Transaction)
{
base.AcquireConnections(Transaction);
connMgr = this.Connections.YourConnName;
con = new OleDbConnection(connMgr.ConnectionString);
}
/*Here you prepare the sql command and open the connection*/
public override void PreExecute()
{
base.PreExecute();
cmd = new OleDbCommand("Some Select", con);
cmd.CommandType = CommandType.Text;
con.Open();
}
/*Here you execute your query for each input row*/
public override void Entrada0_ProcessInputRow(Entrada0Buffer Row)
{
OleDbDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
/*Do your stuff*/
}
}
/*And here you release the connection*/
public override void ReleaseConnections()
{
base.ReleaseConnections();
connMgr.ReleaseConnection(con);
}
HTH
Thanks praveen.
I found the relevant part in your link:
"If you must call the AcquireConnection method of a connection manager that returns an unmanaged object, use an ADO.NET connection manager. When you configure the ADO.NET connection manager to use an OLE DB provider, it connects by using the .NET Framework Data Provider for OLE DB. In this case, the AcquireConnection method returns a System.Data.OleDb.OleDbConnection instead of an unmanaged object. To configure an ADO.NET connection manager for use with an Excel data source, select the Microsoft OLE DB Provider for Jet, specify an Excel file, and enter Excel 8.0 (for Excel 97 and later) as the value of Extended Properties on the All page of the Connection Manager dialog box."
Thanks!

Change Connection String in App.config at runtime

The code below serves to change connection string in App.config at runtime, I found it here but this code did not work for me on Visual Studio 2010 and SQL Server 2008, I could not open the connection to the Northwind database.
using System;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Text;
using System.Windows.Forms;
using System.Xml;
namespace MyNameSpace
{
public partial class FrmConnectionTest : Form
{
public FrmConnectionTest()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
try
{
//Constructing connection string from the inputs
StringBuilder Con = new StringBuilder("Data Source=");
Con.Append(TxtServer.Text);
Con.Append(";Initial Catalog=");
Con.Append(TxtDatabase.Text);
Con.Append(";Integrated Security=SSPI;");
string strCon = Con.ToString();
updateConfigFile(strCon);
//Create new sql connection
SqlConnection Db = new SqlConnection();
//to refresh connection string each time else it will use previous connection string
ConfigurationManager.RefreshSection("connectionStrings");
Db.ConnectionString = ConfigurationManager.ConnectionStrings["con"].ToString();
//To check new connection string is working or not
SqlDataAdapter da = new SqlDataAdapter("select * from employee");
DataTable dt = new DataTable();
da.Fill(dt);
CmbTestValue.DataSource = dt;
CmbTestValue.DisplayMember = "EmployeeID";
}
catch (Exception E)
{
MessageBox.Show(ConfigurationManager.ConnectionStrings["con"].ToString() + ".This is invalid connection", "Incorrect server/Database");
}
}
public void updateConfigFile(string con)
{
//updating config file
XmlDocument XmlDoc = new XmlDocument();
//Loading the Config file
XmlDoc.Load(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
foreach (XmlElement xElement in XmlDoc.DocumentElement)
{
if (xElement.Name == "connectionStrings")
{
//setting the coonection string
xElement.FirstChild.Attributes[2].Value = con;
}
}
//writing the connection string in config file
XmlDoc.Save(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
}
}
}
Using Visual Studio 2010 and SQL Server2008, I got 2 errors for the next line:
SqlDataAdapter da = new SqlDataAdapter("select * from employee");
Error 1 The best overloaded method match for 'System.Data.SqlClient.SqlDataAdapter.SqlDataAdapter(System.Data.SqlClient.SqlCommand)' has some invalid arguments
Error 2 Argument 1: cannot convert from 'string' to 'System.Data.SqlClient.SqlCommand'
Is there any solution to this issue? Thank you.
The error is telling you that you are passing incorrect parameters to your SqlDataAdapter. I think the proper call would be:
SqlDataAdapter da = new SqlDataAdapter("select * from employee", Db);
Edit
It looks like you're creating your connection string from within your program, saving it to your config file, then reading it out of our config file right before you create your SqlDataAdapter. So, when you debug this line:
Db.ConnectionString = ConfigurationManager.ConnectionStrings["con"].ToString();
Double check that Db.ConnectionString actually contains a connection string.
The other thing to do is open up your SQL Server Management Studio and confirm you can connect to the Northwind database from there. Including/alternatively, in Visual Studio, open your "Server Explorer" window and confirm you can create a Data Connection to Northwind by clicking Add Connection and then setting the connection property window to your server and dropping down the combobox to see if it populates with your databases:
Take a look at the available constructors of the SqlDataAdapter class.
There is no constructor overload that accepts just an SQL String.
You need to use one of the other overloads.
For example, there is one that needs an SQL String and a SqlConnection object.
To use it, change your code like this:
SqlDataAdapter da = new SqlDataAdapter("select * from employee", Db);
EDIT:
As BradRem already mentioned in his comment, try a different connection string.
If his example doesn't work for you, you can find more possible examples at http://connectionstrings.com/sql-server-2008.
Do you really have a database called Northwind on your server?
Does the Windows user on your current machine have permissions on the server to access the database? (that's what Integrated Security=SSPI means - your current Windows user is used to access the database!)

Resources