Inside of a Script Task in SSIS, I need to make a call to an SQL database. I have a connection string that was created when I added the database to the data sources folder, however now I'm not sure how to reference it inside the C# code. I know how to do this in the code behind of an ASP website, however it seems that SSIS should have a more direct method.
EDIT
This line of code actually winds up throwing an exception:
sqlConn = (System.Data.SqlClient.SqlConnection)cm.AcquireConnection(Dts.Transaction);
It reads: "Unable to cast COM object of type 'System._ComObject' to class type 'System.Data.SqlClient.SqlConection.'"
you cant use the configurations from a connection manager from inside a script task like:
conectionManager1.exceuteSQLStatment(...)
once you are "inside" the script task you need to access the CM like a variable:
ConnectionManager cm;
System.Data.SqlClient.SqlConnection sqlConn;
System.Data.SqlClient.SqlCommand sqlComm;
cm = Dts.Connections["conectionManager1"];
sqlConn = (System.Data.SqlClient.SqlConnection)cm.AcquireConnection(Dts.Transaction);
sqlComm = new System.Data.SqlClient.SqlCommand("your SQL Command", sqlConn);
sqlComm.ExecuteNonQuery();
cm.ReleaseConnection(sqlConn);
You must check the privider of the connection that your are trying to instantiate.
You can't cast a OleDb.OleDbConnection connection as a SQLClient.SQLConnection, the parameters are different.
Related
I've been stumped on this problem for a while, and although I have searched up my problems online, I haven't had much luck. So in my Android program made in Xamarin, in the button click event, I try to send data to the server, however, I would get this error:
System.InvalidOperationException: Update requires the command clone to have a connection object. The Connection property of the command clone has not been initialized.
I am using this code at this point:
using (SqlConnection connection = new SqlConnection(cs))
{
connection.Open();
SqlDataAdapter dataAdapter = new SqlDataAdapter($"Select * from Room", connection);
SqlCommandBuilder commandBuilder = new SqlCommandBuilder(dataAdapter);
Spinner roomsSPNR = FindViewById<Spinner>(Resource.Id.rooms);
int room = Convert.ToInt32(roomsSPNR.SelectedItem.ToString());
DataRow[] selected = rooms.Tables[0].Select($"RoomNo = {room}");
selected[0][3] = Id;
dataAdapter.Update(rooms); //Line giving the error
}
changeColors(Id);
I'm stumped on this, I can't really figure out why it is doing this. Can anyone help?
I have tried:
Setting the update.connection manually
Making an SQL command and putting the command builder's command into there(There is another error)
Setting the DataAdapter's update command to the method for the command builder
In the DataAdapter's initialization, I have changed the connection to the connection string
Many others that may not have any importance
Edit: Earlier in the code the program is able to read from the server and put it into 'rooms. On the other hand, I'm not familiar with making web services; is that what I need to do to allow it to update the database?
You cannot directly connect with a database in xamarin. You need to first create a webservice and use that web service to insert or fetch data from database.
If you need I will help you with webservices.
I am trying to create to a local database via a mdf file, like so:
scon = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDBFilename=|DataDirectory|\articles.mdf; Integrated Security=True");
scon.Open();
scmd = new SqlCommand("Insert INTO articles(url) VALUES(#url)");
scmd.Parameters.AddWithValue("#url", "http://google.com");
scmd.ExecuteNonQuery();
MY mdf file is in the root folder, and in the debug folder too. When I run the following code I get an error saying the following:
I can't use the full connection path because it's a long url with spaces, here is my file structure:
My database exists:
How can I fix this so I can connect to my database?
Pass the connection object to the SqlCommand constructor
scmd = new SqlCommand("Insert INTO articles(url) VALUES(#url)", scon);
The connectionstring is fine, the error message informs you that it is not possible to execute a command if the database is not known. The SqlConnection contains this information and you need to pass it to your command.
Another possibility is through the
scmd.Connection = scon;
but, personally, I prefer to pass that info in the constructor.
Final but really important note:
SqlConnection and SqlCommand are disposable objects. You should always dispose these kind of objects. The using statement is the correct method
using(scon = new SqlConnection(....))
using(scmd = new SqlCommand("Insert INTO articles(url) VALUES(#url)",scon))
{
scon.Open();
scmd.Parameters.AddWithValue("#url", "http://google.com");
scmd.ExecuteNonQuery();
}
The Problem With Your Code Is That You Have A Command and a Connection But There Is Nothing To Till The Command To Use This Connection Object ... You Can Use The SqlCommand Constructor To Do That
scmd = new SqlCommand("Insert INTO articles(url) VALUES(#url)",scon)
Or Use The Connection Property Of The SqlCommand Class Like This
scmd.Connection = scon
Consider Adding Using To Your SQL Connection ... Or Else You Will Have To Manually Close The Connection By Calling scon.Close();
if You Didn't Do either Of Those You Will Run Into An Exception If Your Tried To Open The Connection Again While It's Already Open
I have tried various forms of the following method to get the next sequence value from an Oracle DB in my asp.net app. The sql statement works fine in Toad (11g). The sql statement includes "Select ... myschema.mySeq.nextval ... from dual. But the error I receive when I get to cmd.ExecuteNonQuery() -- the error is:
>
Exception Details: Oracle.DataAccess.Client.OracleException: ORA-00942: table or view does not exist
<<
Authentication is a very big deal at the place where I am at. Is this a data Access problem or is something incorrect with my method (below)? If something is incorrect with the code below what is the correction I need to make? Note: the app (big app) has hundreds of calls to SPs (which all work fine), so I basically copied the connection string code and used a constant (like they do throughout the app). If I use an SP this works, but I want to not use an SP just straight forward Ado.Net. What is the fix?
public int getNextPositionSequence(string userSeq)
{
OracleConnection conn = new OracleConnection(DaoHelper.GetConnectionString("AuthenticatedOracleConnectionString"));
conn.Open();
conn.ClientId = userSeq;
string sql = "SELECT ddtms.position_seq.nextval from dual";
OracleCommand cmd = new OracleCommand(sql, conn);
object s = cmd.ExecuteNonQuery(); //<<<--- crashes here
conn.Close();
return 1;
}
We are using a c# application (Ranorex) to connect to a Microsoft Access (.mdb) database using an ODBC Connection. During a single run of the code we receive no errors and the connection is made successfully.
Basically the code opens a connection to the DB, retrieves data from the database and then we use the .close method on the database connection when we're done.
However when the code is run continually in a loop after a couple of days the following error is displayed:
"Thread Failed To Start".
This happens at the point the ODBC connection is (attempted) to open.
Does anybody have any suggestions as how to fix this?
Thanks
This is just an example. I cannot answer your question with a direct reference to your code, because, well there is no code to look at. However, the pattern to follow when working with expensive resources like database connections is always the same: Create, Open, Use, Close, Destroy
using(OdbcConnection con = new OdbcConnection(conString))
using(OdbcCommand cmd = new OdbcCommand(commantText, con))
{
OdbcDataAdapter da = new OdbcDataAdapter(cmd);
con.Open();
DataSet ds = new DataSet();
da.Fill(ds, "Table");
dataGridView1.DataSource = ds.Tables[0];
}
The using statement play a fundamental role here. When the code exits from the using block, the command is disposed, the connection is closed and then disposed. Also if you get an Exception in the middle of the using block. It is a very handy replacemente for writing try{....}finally{close/dispose}. Of course I cannot claim that this will resolve your problems, but nevertheless this is the correct first aid to apply to your code.
Hello I'm trying to run a simple sql command on a DB from MS VS C# 2010 and I have encountered a error I have never seen before the relevant code is:
SqlConnection comCon = new SqlConnection(#"Data Source=C:\\Users\\George\\Desktop\\programming\\C#workspace\\Projects\\Examen\\Examen\\Companie.mdf;Initial Catalog=Proiect;Integrated Security=True");
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "UPDATE Proiect SET Buget = Buget + 500 WHERE (Buget > 0)";
cmd.Connection = comCon;
comCon.Open();
Console.WriteLine(cmd.ExecuteNonQuery().ToString());
comCon.Close();
And the error is Keyword not supported: 'data source'
The main problem is that I'm not used to creating these sqlconnections by hand so please tell me if I'm missing something.
You are using the wrong structure. To attach a database file, you need to use the following structure:
SqlConnection sqlConnection =
"Server=DatabaseServerName;AttachDbFilename=d:\Database\Database.mdf;
Database=DatabaseName; Trusted_Connection=Yes";
You need to have the right permissions on both the target file and database server to attach the databse and establish the connection.
Server=.\SQLExpress;AttachDbFilename=|DataDirectory|mydbfile.mdf;Database=dbname; Trusted_Connection=Yes;
If it's not an ASP.NET application don't use the DataDirectory syntax and just use the full c:... path.